Extracting Certain XML Elements with PHP SimpleXML

Posted by Peter on Stack Overflow See other posts from Stack Overflow or by Peter
Published on 2010-04-20T11:20:54Z Indexed on 2010/04/20 11:23 UTC
Read the original article Hit count: 332

Filed under:
|
|
|

I am having some problems parsing this piece of XML using SimpleXML. There is always only one Series element, and a variable number of Episode elements beneath. I want to parse XML so I can store the Series data in one table, and all the Episode data in another table.

XML:

<Data>
    <Series>
        <id>80348</id>
        <Genre>|Action and Adventure|Comedy|Drama|</Genre>
        <IMDB_ID>tt0934814</IMDB_ID>
        <SeriesID>68724</SeriesID>
        <SeriesName>Chuck</SeriesName>
        <banner>graphical/80348-g.jpg</banner>
    </Series>
    <Episode>
        <id>935481</id>
        <Director>Robert Duncan McNeill</Director>
        <EpisodeName>Chuck Versus the Third Dimension 2D</EpisodeName>
        <EpisodeNumber>1</EpisodeNumber>
        <seasonid>27984</seasonid>
        <seriesid>80348</seriesid>
    </Episode>
    <Episode>
        <id>935483</id>
        <Director>Robert Duncan McNeill</Director>
        <EpisodeName>Buy More #15: Employee Health</EpisodeName>
        <EpisodeNumber>2</EpisodeNumber>
        <seasonid>27984</seasonid>
        <seriesid>80348</seriesid>
    </Episode>
</Data>

When I attempt to access just the first Series element and child nodes, or iterate through the Episode elements only it does not work. I have also tried to use DOMDocument with SimpleXML, but could not get that to work at all.

PHP Code:

<?php
    if(file_exists('en.xml'))
    {
        $data = simplexml_load_file('en.xml');
        foreach($data as $series)
        {
            echo 'id: <br />' . $series->id;
            echo 'imdb: <br />' . $series->IMDB_ID;
        }
    }
?>

Output:

id:80348
imdb:tt0934814
id:935481
imdb:
id:1534641
imdb:

Any help would be greatly appreciated.

© Stack Overflow or respective owner

Related posts about php5

Related posts about Xml