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];
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 $variablewill 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,
$updateVerand$updateVerHumanare both still objects when you turn them to JSON.$updateVer = (string)$xml->version; $updateVerHuman = (string)$xml->humanVersion;should give the expected result.