Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting cdata content while parsing xml file

I have an xml file

<?xml version="1.0" encoding="utf-8"?>
<xml>
    <events date="01-10-2009" color="0x99CC00" selected="true"> 
       <event>
            <title>You can use HTML and CSS</title>
            <description><![CDATA[This is the description ]]></description>
        </event>
    </events>
</xml>

I used xpath and and xquery for parsing the xml.

$xml_str = file_get_contents('xmlfile');
$xml = simplexml_load_string($xml_str);
if(!empty($xml))
{
    $nodes = $xml->xpath('//xml/events');
}

i am getting the title properly, but iam not getting description.How i can get data inside the cdata

like image 471
Warrior Avatar asked Sep 06 '10 09:09

Warrior


People also ask

How do I ignore CDATA?

There is no way to ignore the CDATA tag - it's part of the xml spec and parsers should honour it. If you don't like the idea of this answer to your earlier question, you could get the contents of the CDATA section and parse it as XML again. However, this is highly not recommended!

How can the content of XML be parsed?

Serializes DOM trees, converting them into strings containing XML. Constructs a DOM tree by parsing a string containing XML, returning a XMLDocument or Document as appropriate based on the input data. Loads content from a URL; XML content is returned as an XML Document object with a DOM tree built from the XML itself.

What does the parser do with the CDATA section of an XML document?

A CDATA section is used to mark a section of an XML document, so that the XML parser interprets it only as character data, and not as markup. It comes handy when one XML data need to be embedded within another XML document.


1 Answers

SimpleXML has a bit of a problem with CDATA, so use:

$xml = simplexml_load_file('xmlfile', 'SimpleXMLElement', LIBXML_NOCDATA);
if(!empty($xml))
{
    $nodes = $xml->xpath('//xml/events');
}
print_r( $nodes );

This will give you:

Array
(
    [0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [date] => 01-10-2009
                    [color] => 0x99CC00
                    [selected] => true
                )

            [event] => SimpleXMLElement Object
                (
                    [title] => You can use HTML and CSS
                    [description] => This is the description 
                )

        )

)
like image 188
ocodo Avatar answered Oct 07 '22 05:10

ocodo