[solution] Parsing XML to an array

By.

min read

My profile

Share this:

Perhaps even better:

http://us2.php.net/manual/en/simplexml.examples.php

[code:1:f66949fd39]<?php
$xmlstr = <<<XML
<?xml version=’1.0′ standalone=’yes’?>
<movies>
<movie>
<title>PHP: Behind the Parser</title>
<characters>
<character>
<name>Ms. Coder</name>
<actor>Onlivia Actora</actor>
</character>
<character>
<name>Mr. Coder</name>
<actor>El ActÓr</actor>
</character>
</characters>
<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>
<great-lines>
<line>PHP solves all my web problems</line>
</great-lines>
<rating type=”thumbs”>7</rating>
<rating type=”stars”>5</rating>
</movie>
</movies>
XML;
?>
[/code:1:f66949fd39][code:1:f66949fd39]<?php
include ‘example.php’;

$xml = new SimpleXMLElement($xmlstr);

echo $xml->movie[0]->plot; // “So this language. It’s like…”
?>
[/code:1:f66949fd39][code:1:f66949fd39]<?php
include ‘example.php’;

$xml = new SimpleXMLElement($xmlstr);

/* Access the <rating> nodes of the first movie.
* Output the rating scale, too. */
foreach ($xml->movie[0]->rating as $rating) {
switch((string) $rating[’type’]) { // Get attributes as element indices
case ‘thumbs’:
echo $rating, ‘ thumbs up’;
break;
case ‘stars’:
echo $rating, ‘ stars’;
break;
}
}
?>
[/code:1:f66949fd39]

Share this:

Leave a Reply

Your email address will not be published. Required fields are marked *