How-to: Fix simplexml CDATA problem in PHP

Source: Internet
Author: User

Private function xml_to_array ($ XML ){

$ Xmlarray = simplexml_load_file ($ XML, 'simplexmlelement', libxml_nocdata );

Foreach ($ xmlarray as $ key => $ item ){

$ Array [$ key] = $ this-> struct_to_array (array) $ item );

}

Return $ xmlarray;

}

Private function struct_to_array ($ item ){

If (! Is_string ($ item )){

$ Item = (array) $ item;

Foreach ($ item as $ key => $ Val ){

$ Item [$ key] = $ this-> struct_to_array ($ Val );

}

}

Return $ item;

}

Call

Var_dump ($ this-> xml_to_array (realpath ('Public/en_51j_passive_11098_4803845.xml ')));


If you 've used the simplexml functions in PHP, you may have noticed some strange things happening with CDATA values in your xml file/string. all I needed to do was extract the value of my CDATA fields, however these were always coming back blank in the structure that simplexml_load_file returns.

Finally, after hours of trawling Google, I 've come up with the following solution:

$xml = simplexml_load_file($this->filename,'SimpleXMLElement', LIBXML_NOCDATA);

Use this line of code when you are loading the XML file into the simplexml object. The key isLibxml_nocdataOption as the third parameter. This returns the XML Object with all the CDATA converted into strings. You can read about this in the PHP manual.

This solved all the problems I was having getting CDATA values out of simplexml in PHP. Hope it helps someone.

 

See: http://blog.evandavey.com/2008/04/how-to-fix-simplexml-cdata-problem-in-php.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.