How-To: Fix SimpleXML CDATA problem in php
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;
}
调用
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 is the LIBXML_NOCDATA option as the third parameter. This returns the XML object with all the CDATA data 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.
详见:http://blog.evandavey.com/2008/04/how-to-fix-simplexml-cdata-problem-in-php.html