Reputation: 836
Below you will find my xml document:
<?xml version="1.0" encoding="ISO-8859-1"?>
<app>
<version>0925</version>
<humanVersion>0.9.25</humanVersion>
</app>
Here is my php:
$completeurl = "ota/shingle/shingle.xml";
$xml = simplexml_load_file($completeurl);
$updateVer = $xml->version;
$updateVerHuman = $xml->humanVersion;
I am taking the php variables and putting them into a json string, here is the output:
{"updateVer":{"0":"0925"},"updateVerHuman":{"0":"0.9.25"}}
Why is the updateVer and updateVerHuman data enclosed in {} and contains "0":?? I would like only the data in that value. How do I achieve this?
I have tried this but it produces the same result:
$updateVer = $xml->version[0];
$updateVerHuman = $xml->humanVersion[0];
Upvotes: 0
Views: 1726
Reputation: 97948
When you access any child element (or even attribute) with SimpleXML, you get back another SimpleXML object - this is why you can write things like $node->child->grand_child
.
In order to get just the string content of a particular bit of XML, you need to "cast" the SimpleXML object to a string, using (string)$variable
.
Sometimes, this will happen for you - notably, since you can't echo anything other than a string, echo $variable
will always cast to a string for you. However, as a rule of thumb, always cast SimpleXML objects to string to avoid later confusion.
In your example, $updateVer
and $updateVerHuman
are both still objects when you turn them to JSON. $updateVer = (string)$xml->version; $updateVerHuman = (string)$xml->humanVersion;
should give the expected result.
Upvotes: 4