note 84365 added to ref.simplexml

From: Date: Thu, 10 Jul 2008 14:07:10 +0000
Subject: note 84365 added to ref.simplexml
Groups: php.notes 
Request: Send a blank email to php-notes+get-141365@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 &amp; 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 ?> ---- Server IP: 92.48.100.16 Probable Submitter: 217.154.203.18 ---- Manual Page -- http://www.php.net/manual/en/ref.simplexml.php Edit -- https://master.php.net/note/edit/84365 Del: integrated -- https://master.php.net/note/delete/84365/integrated Del: useless -- https://master.php.net/note/delete/84365/useless Del: bad code -- https://master.php.net/note/delete/84365/bad+code Del: spam -- https://master.php.net/note/delete/84365/spam Del: non-english -- https://master.php.net/note/delete/84365/non-english Del: in docs -- https://master.php.net/note/delete/84365/in+docs Del: other reasons-- https://master.php.net/note/delete/84365 Reject -- https://master.php.net/note/reject/84365 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#141365) next »