Tips : Debug SimpleXML developement with CDATA

We must sometimes develop some applications that be able to manage xml node with php’s extension, SimpleXml.
So we have sometimes a problem on debug with CDATA… with non output data… why ? because var_dump and other print_r doesn’t cast the datas.

So if we have this code :

$xml_string = "
<?xml version=’1.0′ standalone=’yes’?>
<movies>
<movie>
<title>PHP: Behind the Parser</title>
</movie>
</movies>”;

$xml_data = simplexml_load_string($xml_string);
echo $xml_data->movie->title;
print_r($xml_data->movie->title);
var_dump($xml_data->movie->title);
?>

The output will be this one :


PHP: Behind the Parser
SimpleXMLElement Object
(
[0] => PHP: Behind the Parser
)
object(SimpleXMLElement)#2 (1) {
[0]=>
string(22) “PHP: Behind the Parser”
}

Ok so what are the output with CDATA (protect specials characters)


$xml_string = "
<?xml version=’1.0′ standalone=’yes’?>
<movies>
<movie>
<title><![CDATA[PHP: Behind the Parser]]></title>
</movie>
</movies>”;

$xml_data = simplexml_load_string($xml_string);

echo $xml_data->movie->title;
print_r($xml_data->movie->title);
var_dump($xml_data->movie->title);
?>

Output :

PHP: Behind the Parser
SimpleXMLElement Object
(
)
object(SimpleXMLElement)#2 (0) {
}


The “echo” cast directly the data’s but not the “print_r” and the “var_dump“.

So the code will be :

$xml_data = simplexml_load_string($xml_string);

echo $xml_data->movie->title;
print_r((string) $xml_data->movie->title);
var_dump((string)$xml_data->movie->title);
?>

And the output :

PHP: Behind the Parser
PHP: Behind the Parser
string(22) “PHP: Behind the Parser”


About this entry