Note that there are some explanatory texts on larger screens.

plurals
  1. POIssue with JSON
    primarykey
    data
    text
    <p>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.</p> <p>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 ;)</p> <h3>tracker.xml</h3> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;tracker&gt; &lt;student&gt; &lt;id&gt;0425655&lt;/id&gt; &lt;lname&gt;Doe&lt;/lname&gt; &lt;fname&gt;John&lt;/fname&gt; &lt;/student&gt; &lt;student&gt; &lt;id&gt;0123456&lt;/id&gt; &lt;lname&gt;Smith&lt;/lname&gt; &lt;fname&gt;Jane&lt;/fname&gt; &lt;/student&gt; &lt;/tracker&gt; </code></pre> <h3>xml.php</h3> <pre><code>class xml { private $path; public function __construct($path) { $this-&gt;path = $path; } public function xmlParse() { $xml = simplexml_load_file($this-&gt;path); return json_encode($xml-&gt;children()); } } </code></pre> <h3>json.php</h3> <pre><code>class json { private $xmlArray; public function __construct($xmlArray) { $this-&gt;xmlArray = $xmlArray; } public function getJSON() { $json = json_decode($this-&gt;xmlArray); foreach($json-&gt;student as $v) { return 'ID: '.$v-&gt;id.'Last: '.$v-&gt;lname.'First: '.$v-&gt;fname; } } } </code></pre> <p>I know I can pass <code>true</code> as a second parameter to <code>json_decode()</code>, but I wanted to work with objects.</p> <p>Here's the output for the <code>json_decode()</code> (after passing it through getJSON for formatting):</p> <pre><code>{ "student": [ { "id": "0425655", "lname": "Doe", "fname": "John" }, { "id": "0123456", "lname": "Smith", "fname": "Jane" } ] } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload