Get XML data with Xpath & Curl

2010-01-16 @ 14:58

There are several ways to get and manage XML data from an RSS feed in PHP. XPath is recommended for this type of problem. All servers do not support simplexml_load_file, but it is possible to get XML data with Curl instead, which will be much safer.

Example

This example is downloading data from an XML file from an RSS feed by using XPath. The XML file is downloaded with Curl, so make sure it is enabled on the server that runs the script. The titles are printed out, just to show that it works. Copy, paste and run the code on a server and it should work instantly. The RSS feed I choose for this example is WordPress development blog.

<?php
function get_url($url)
{
     $curl = curl_init();
     curl_setopt($curl, CURLOPT_HEADER, 0);
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($curl, CURLOPT_URL, $url);
     $data = curl_exec($curl);
     curl_close($curl);
     return $data;
}

function get_url_data()
{
     $xml_content = get_url("http://wordpress.org/development/feed/");
     $dom = new DOMDocument();
     @$dom->loadXML($xml_content);
     $xpath = new DomXPath($dom);
     $content_title = $xpath->query('//channel//title/text()');
     return $content_title;
}

function print_url_data()
{
     $content = get_url_data();
     foreach ($content as $value)
     {
          $output .= $value->nodeValue . "<br />";
     }
     return $output;
}

echo print_url_data();
?>

Change Xpath to get the title, description and link

The example above prints out the titles. You might need to print out URL or descriptions as well. Change the bold part with the Xpath query of your choice:

//channel//title/text()
//channel//description/text()
//channel//link/text()
Share

Leave a reply