I have a problem with function simplexml_load_string. I want to convert XML string to an array. There is my script:
$xml_string = file_get_contents($xml_file_name, LIBXML_NOCDATA);
$xml = simplexml_load_string($xml_string, null, LIBXML_NOCDATA);
$xml = json_decode(json_encode($xml), true);
and this is a part of my XML file:
<p id="1">test1</p>
<p id="2">test2</p>
<p id="3">test3</p>
<p id="5">test5</p>
<p id="10">test10</p>
<p id="13">test13</p>
After convert, my array looks like that:
array(6) {
[0]=>
string(10) "test1"
[1]=>
string(18) "test2"
[2]=>
string(24) "test3"
[3]=>
string(24) "test5"
[4]=>
string(11) "test10"
[5]=>
string(9) "test13"
}
And now, look at the indexes. Before convert indexes were: 1, 2, 3, 5, 10, 13. After convert, I got: 0, 1, 2, 3, 4, 5. Where is a problem? Why are these indexes rename by function simplexml_load_string?
Thanks.
You have to understand what you are really doing here. After calling simplexml_load_string
you have an object of type SimpleXMLElement
.
http://php.net/manual/function.simplexml-load-string.php http://php.net/manual/class.simplexmlelement.php
This object contains all information from the XML including the id-attributes.
If you json_encode
and json_decode
the object the attributes are dropped, as the JSON representation of the SimpleXMLElement most probably throws the attributes away.
Ok so what you have to do is: You want to cast the SimpleXMLElement
to an array without loosing attibute data. There are a lot of possibilities to do this, including custom implementation.
However I guess you should find an answer here: