I am trying to have PHP read an XML file and then convert it to JSON to use in some classes that I wrote. The problem I am having is it will not loop thru all XML nodes.
For some reason it will only return one node and not both. My guess is maybe my JSON object is not formatted correctly. I have been messing with this for about 2 days, ugh! I am new to this so go easy on me 😉
tracker.xml
<?xml version="1.0" encoding="UTF-8"?>
<tracker>
<student>
<id>0425655</id>
<lname>Doe</lname>
<fname>John</fname>
</student>
<student>
<id>0123456</id>
<lname>Smith</lname>
<fname>Jane</fname>
</student>
</tracker>
xml.php
class xml
{
private $path;
public function __construct($path)
{
$this->path = $path;
}
public function xmlParse()
{
$xml = simplexml_load_file($this->path);
return json_encode($xml->children());
}
}
json.php
class json
{
private $xmlArray;
public function __construct($xmlArray)
{
$this->xmlArray = $xmlArray;
}
public function getJSON()
{
$json = json_decode($this->xmlArray);
foreach($json->student as $v)
{
return 'ID: '.$v->id.'Last: '.$v->lname.'First: '.$v->fname;
}
}
}
I know I can pass true as a second parameter to json_decode(), but I wanted to work with objects.
Here’s the output for the json_decode() (after passing it through getJSON for formatting):
{
"student": [
{
"id": "0425655",
"lname": "Doe",
"fname": "John"
},
{
"id": "0123456",
"lname": "Smith",
"fname": "Jane"
}
]
}
returnimmediately, well, returns from the current function. You wantechofor debugging, as inIf you want to return the result, either just return the JSON object or parse it into an array or string.