How to Read an XML File in PHP with SimpleXML
Alternatively, this could be called "How to Read an RSS Feed in PHP with SimpleXML." Most of you will be using this code to read an RSS feed and place it on your website (i.e. your Twitter feed).
The code is actually pretty simple. Just make sure you have SimpleXML on your server.
$xml = @simplexml_load_file('location of xml file');for ($n = 0; $n < 5; $n++) { $title = $xml->channel->item[$n]->title; $description = $xml->channel->item[$n]->description; $guid = $xml->channel->item[$n]->guid; $pubDate = date("l, F j, Y \a\\t g:iA", strtotime($xml->channel->item[0]->pubDate)); echo '' . $title . '' . $description . '' . $guid . '' . $pubDate . ''; }
As you can see, this short bit of code is extremely simple. Line 1 is simply calling the XML file. Line 2 begins a for loop that goes through the first 5 entries in the XML file. You can change the 5 to any number you want. Lines 3-6 are taking each element of the items and saving them to a variable. In line 6 you'll see I added in a date function to format the date in the RSS feed for output. Line 8 is writing all the data to the browser. Of course, you can change the way you want it outputted by simply changing the HTML around the variables.
Very easy to do and easy to adapt to any XML file.

Post a Comment
All fields are required.