Powered by emcons.net

How to use XPath in PHP

From How2s

Here are a few simple PHP examples using XPATH:

Retrieve RSS Items of a Wordpress Blog for a specific search term

function get_item($keywords) {
	// define url
	$url = "http://somewordpressblog.com/feed/?s=" . urlencode($keywords) . "&submit=";
	
	// retrieve results
	if($xml = simplexml_load_file($url, 'SimpleXMLElement', LIBXML_NOCDATA)) {
		$result["title"] 			= $xml->xpath("/rss/channel/item/title");
		$result["link"]	 			= $xml->xpath("/rss/channel/item/link");
		$result["content"] 			= $xml->xpath("/rss/channel/item/content:encoded/text()");
		
		return $result;	
	} else
		return false;	
}

Note: use 'SimpleXMLElement', LIBXML_NOCDATA to make sure the CDATA block within the content node is not being ignored.

The above can also be written as:

if($xml = simplexml_load_file($url, 'SimpleXMLElement', LIBXML_NOCDATA)) {
		$i = 1;
		foreach($xml->channel->item as $item){
		  $result[$i]["title"] 		= $item->title;
		  $result[$i]["link"] 		= $item->link;
		  $result[$i]["description"] 	= $item->description;
		  $i++;
		}
		return $result;	
}

NOTE: the lower section will create one element per item whereas the above section shows one element per node.