I want to convert below XML to PHP array. Any suggestions on how I can do this?
$array = json_decode(json_encode((array)simplexml_load_string($xml)),true);
Another option is the SimpleXML extension (I believe it comes standard with most php installs.)
http://php.net/manual/en/book.simplexml.php
The syntax looks something like this for your example
$xml = new SimpleXMLElement($xmlString);
echo $xml->bbb->cccc->ffffdd['Id'];
echo $xml->bbb->cccc->eeee['name'];
// or...........
foreach ($xml->bbb->cccc as $element) {
foreach($element as $key => $val) {
echo "{$key}: {$val}";
}
}
The method used in the accepted answer drop attributes when encountering child elements with only a text node. For example:
$xml = '<container><element attribute="123">abcd</element></container>';
print_r(json_decode(json_encode(simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA)),1));
Array
(
[element] => abcd
)
My solution (and I wish I could give credit here because I'm sure I adapted this from something):
function XMLtoArray($xml) {
$previous_value = libxml_use_internal_errors(true);
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->preserveWhiteSpace = false;
$dom->loadXml($xml);
libxml_use_internal_errors($previous_value);
if (libxml_get_errors()) {
return [];
}
return DOMtoArray($dom);
}
function DOMtoArray($root) {
$result = array();
if ($root->hasAttributes()) {
$attrs = $root->attributes;
foreach ($attrs as $attr) {
$result['@attributes'][$attr->name] = $attr->value;
}
}
if ($root->hasChildNodes()) {
$children = $root->childNodes;
if ($children->length == 1) {
$child = $children->item(0);
if (in_array($child->nodeType,[XML_TEXT_NODE,XML_CDATA_SECTION_NODE])) {
$result['_value'] = $child->nodeValue;
return count($result) == 1
? $result['_value']
: $result;
}
}
$groups = array();
foreach ($children as $child) {
if (!isset($result[$child->nodeName])) {
$result[$child->nodeName] = DOMtoArray($child);
} else {
if (!isset($groups[$child->nodeName])) {
$result[$child->nodeName] = array($result[$child->nodeName]);
$groups[$child->nodeName] = 1;
}
$result[$child->nodeName][] = DOMtoArray($child);
}
}
}
return $result;
}
$xml = '
<aaaa Version="1.0">
<bbb>
<cccc>
<ffffdd id="123" />
<eeee name="john" age="24" />
<ffff type="employee">Supervisor</ffff>
</cccc>
</bbb>
</aaaa>
';
print_r(XMLtoArray($xml));
Array
(
[aaaa] => Array
(
[@attributes] => Array
(
[Version] => 1.0
)
[bbb] => Array
(
[cccc] => Array
(
[ffffdd] => Array
(
[@attributes] => Array
(
[id] => 123
)
)
[eeee] => Array
(
[@attributes] => Array
(
[name] => john
[age] => 24
)
)
[ffff] => Array
(
[@attributes] => Array
(
[type] => employee
)
[_value] => Supervisor
)
)
)
)
)