Page 1 of 1

SimpleXMl problem HELP please

Posted: Thu Jan 22, 2009 4:15 am
by iwsyang
Hers is an example:
<?php
$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<movies>
<movie>
<title>CSS</title>
<name>Mr. Coder</name>
<actor>El Act&#211;r</actor>
<plot>
So, this language. It\'s like, a programming language. Or is it a
scripting language? All is revealed in this thrilling horror spoof
of a documentary.
</plot>
<rating type="thumbs">7</rating>
<rating type="stars">5</rating>
</movie>

<movie>
<title>java</title>
<name>Ms. Coder</name>
<actor>Onlivia Actora</actor>
<plot>
So, this language. It\'s like, a programming language. Or is it a
scripting language? All is revealed in this thrilling horror spoof
of a documentary.
</plot>
<rating type="thumbs">7</rating>
<rating type="stars">5</rating>
</movie>
</movies>
XML;
$xml = new SimpleXMLElement($xmlstr);
echo('<pre>');
var_dump($xml->movie);
echo('<br/>');
echo('</pre>');
?>

In this situation, it will print out the structure of the first movie. but if you change to var_dump($xml->movie[0]), it will also print out the first movie.
now, if I change to this :foreach ($xml->movie as $movie) {var_dump($movie);} it will output both movies.

So, my question is what on earth $xml->movie refer to? the first movie or the nodelist of 2 movies? Thanks

Re: SimpleXMl problem HELP please

Posted: Thu Jan 22, 2009 11:50 am
by machinehead933
Looking at your example:

Code: Select all

$xml->movie
This refers to an array of all of the <movie> items in the XML feed. The reason

Code: Select all

var_dump($xml->movie)
only displays the first movie is because you haven't specified for PHP to do anything else, so it defaults to spitting out the first <movie> tag it finds. As you discovered, $xml->movie[0] yields the same result, and $xml->movie[1] will display the 2nd movie.

Now the reason

Code: Select all

($xml->movie as $movie)
Displays both movies is because you have told PHP to loop through each occurrence of <movie> in the XML as provided and then to do "something" with it. In this case you've chosen to var_dump that something. So PHP is passing first var_dump($xml->movie[0]) and then var_dump($xml->movie[1])