0

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.

1
  • 1, 2, 3, 5, 10, 13 are not indexes, they are attributes, you should parse the XML and get their value. Commented Nov 3, 2017 at 15:03

1 Answer 1

1

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:

Recursive cast from SimpleXMLObject to Array

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.