Blank CDATA with PHP and SimpleXML

By default CDATA blocks in XML requests using SimpleXML are not returned and the node is blank. Here is an example using an RSS feed from DevShed.

SimpleXML Default

Request

$url = 'http://www.devshed.com/rss-feeds-11.xml';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3); 

// Execute, close connection
$curl_result = curl_exec($ch);
curl_close($ch); 

// Convert to SimpleXML
$xml = new SimpleXMLElement($curl_result);
print_r($xml);

Response

Notice that the <description> node is blank.

[0] => SimpleXMLElement Object
(
	[title] => Exception Handling in PHP
	[pubDate] => Mon, 04 Jan 2010 09:00:01 -0500
	[link] => http://www.devshed.com/c/a/PHP/Exception-Handling-in-PHP/?kc=rss
	[description] => SimpleXMLElement Object
		(
		)
	[guid] => http://www.devshed.com/c/a/PHP/Exception-Handling-in-PHP/?kc=rss
)

SimpleXML using simplexml_load_string

Request

$url = 'http://www.devshed.com/rss-feeds-11.xml';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3); 

// Execute, close connection
$curl_result = curl_exec($ch);
curl_close($ch); 

$xml = simplexml_load_string($curl_result, 'SimpleXMLElement', LIBXML_NOCDATA);
print_r($xml);

Response

<description> is now filled in.

[0] => SimpleXMLElement Object
(
	[title] => Exception Handling in PHP
	[pubDate] => Mon, 04 Jan 2010 09:00:01 -0500
	[link] => http://www.devshed.com/c/a/PHP/Exception-Handling-in-PHP/?kc=rss
	[description] =>
In this second part of a two-part series on error and exception handling in PHP, we focus specifically on handling exceptions. This article is excerpted from chapter 8 of the book Beginning PHP and Oracle: From Novice to Professional, written by W. Jason Gilmore and Bob Bryla (Apress; ISBN: 1590597702).
-  Exception Handling
Languages such as Java, C#, and Python have long been heralded for their efficient error-management abilities, accomplished through the use of exception handling. If you have prior experience working with exception handlers, you likely scratch your head when working with any l...
	[guid] => http://www.devshed.com/c/a/PHP/Exception-Handling-in-PHP/?kc=rss
)

Demos

SimpleXML Default
SimpleXML using simplexml_load_string

Download

Zip Archive

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter

Related Posts

Tags: , ,

Leave a Reply





Donate

If you found this article useful and would like to see more like it this please consider making a donation.

Sponsors