Issue with JSON
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 $开发者_如何学JAVApath;
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"
}
]
}
return
immediately, well, returns from the current function. You want echo
for debugging, as in
foreach($json->student as $v)
{
echo 'ID: '.$v->id.'Last: '.$v->lname.'First: '.$v->fname;
}
If you want to return the result, either just return the JSON object or parse it into an array or string.
That JSON string looks right to me, problem lies with the return
statement - as you're looping through an array, use echo
instead.
Regarding your JSON
I reformatted your output. As you can see, there are two nodes under "student". Perhaps you missed the [
and ]
characters.
Format your JSON next time to get a better idea of what's going on. :)
Regarding your function
You also might have missed it because your debug output is broken:
foreach($json->student as $v)
{
return 'ID: '.$v->id.'Last: '.$v->lname.'First: '.$v->fname;
}
You return after the first iteration.
Try:
$output = '';
foreach ($json->student as $v) {
$output .= "ID: {$v->id} Last: {$v->lname} First: {$v->fname}\n";
}
return $output;
To be honest, though, I'd expect a function named getJSON()
to return, well... JSON. Not some author-written string. Your classes and functions are poorly named overall.
Perhaps your function should look like this:
public function getJSON()
{
$json = json_decode($this->xmlArray);
// some debug output for development
foreach ($json->student as $v) {
echo "ID: {$v->id} Last: {$v->lname} First: {$v->fname}\n";
}
return $json;
}
精彩评论