PHP parse XML

XML sample (songs.xml):


<songs>

    <song date="2010-03-10 10:20:15">

        <title>A Day in the Life</title>

        <artist>The Beatles</artist>

    </song>

    <song date="2012-05-15 12:30:30">

        <title>In The Ghetto</title>

        <artist>Elvis Presley</artist>

    </song>

    <song date="2014-07-20 14:40:45">

        <title>Live Forever</title>

        <artist>Oasis</artist>

    </song>

</songs>

PHP code to parse XML:


<?php

$songs = simplexml_load_file('xml/songs.xml');



echo '<ul>';

foreach ($songs as $song):

	echo '<li>'.$song->title.' by <strong>'.$song->artist.'</strong> ('.$song['date'].')</li>';

endforeach;

echo '</ul>';

?>

Output:

  • A Day in the Life by The Beatles (2010-03-10 10:20:15)
  • In The Ghetto by Elvis Presley (2012-05-15 12:30:30)
  • Live Forever by Oasis (2014-07-20 14:40:45)

Leave a Comment