Skip to content

Instantly share code, notes, and snippets.

@troelskn
Last active January 5, 2017 18:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save troelskn/221aec3bfdfd3d86d069 to your computer and use it in GitHub Desktop.
Save troelskn/221aec3bfdfd3d86d069 to your computer and use it in GitHub Desktop.
xml2assoc.php
<?php
// Take XmlReader node and read it into an assoc array
function xml2assoc($xml) {
$buffer = null;
while ($xml->read()) {
switch ($xml->nodeType) {
case XMLReader::END_ELEMENT:
return $buffer;
case XMLReader::ELEMENT:
if (!is_array($buffer)) {
$buffer = array();
}
$buffer[$xml->name] = $xml->isEmptyElement ? null : xml2assoc($xml);
if ($xml->hasAttributes) {
while ($xml->moveToNextAttribute()) {
$buffer[$xml->name] = $xml->value;
}
}
break;
case XMLReader::TEXT:
case XMLReader::CDATA:
if (!is_string($buffer)) {
$buffer = "";
}
$buffer .= $xml->value;
}
}
return $buffer;
}
@bushev
Copy link

bushev commented Jan 5, 2017

Unfortunately, only last item of array is presented in result assoc array.

<images>
  <image>
   http://localhost:5000/images/object-demo-image-1.jpg
  </image>
  <image>
   http://localhost:5000/images/object-demo-image-2.jpg
  </image>
</images>

->>

[images] => Array
        (
            [image] => http://localhost:5000/images/object-demo-image-2.jpg
        )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment