note 84365 modified in ref.simplexml by danbrown
| From: | danbrown@php.net | Date: | Mon, 18 May 2009 01:10:36 +0000 |
| Subject: | note 84365 modified in ref.simplexml by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-155488@lists.php.net to get a copy of this message | ||
There seems to be a lot of talk about SimpleXML having a "problem" with CDATA, and writing
functions to rip it out, etc. I thought so too, at first, but it's actually behaving just fine
under PHP 5.2.6
The key is noted above example #6 here:
http://uk2.php.net/manual/en/simplexml.examples.php
"To compare an element or attribute with a string or pass it into a function that requires a
string, you must cast it to a string using (string). Otherwise, PHP treats the element as an
object."
If a tag contains CDATA, SimpleXML remembers that fact, by representing it separately from the
string content of the element. So some functions, including print_r(), might not show what you
expect. But if you explicitly cast to a string, you get the whole content.
<?php
$xml = simplexml_load_string('<foo>Text1 & XML entities</foo>');
print_r($xml);
/*
SimpleXMLElement Object
(
[0] => Text1 & XML entities
)
*/
$xml2 = simplexml_load_string('<foo><![CDATA[Text2 & raw
data]]></foo>');
print_r($xml2);
/*
SimpleXMLElement Object
(
)
*/
// Where's my CDATA?
// Let's try explicit casts
print_r( (string)$xml );
print_r( (string)$xml2 );
/*
Text1 & XML entities
Text2 & raw data
*/
// Much better
?>
--was--
There seems to be a lot of talk about SimpleXML having a "problem" with CDATA, and writing
functions to rip it out, etc. I thought so too, at first, but it's actually behaving just fine
under PHP 5.2.6
The key is noted above example #6 here:
http://uk2.php.net/manual/en/simplexml.examples.php
"To compare an element or attribute with a string or pass it into a function that requires a
string, you must cast it to a string using (string). Otherwise, PHP treats the element as an
object."
If a tag contains CDATA, SimpleXML remembers that fact, by representing it separately from the
string content of the element. So some functions, including print_r(), might not show what you
expect. But if you explicitly cast to a string, you get the whole content.
<?php
$xml = simplexml_load_string('<foo>Text1 & XML entities</foo>');
print_r($xml);
/*
SimpleXMLElement Object
(
[0] => Text1 & XML entities
)
*/
$xml2 = simplexml_load_string('<foo><![CDATA[Text2 & raw
data]]></foo>');
print_r($xml2);
/*
SimpleXMLElement Object
(
)
*/
// Where's my CDATA?
// Let's try explicit casts
print_r( (string)$xml );
print_r( (string)$xml2 );
/*
Text1 & XML entities
Text2 & raw data
*/
// Much better
?>
http://php.net/manual/en/ref.simplexml.php