How-To: Fix SimpleXML CDATA problem in php

本文介绍了一种有效的方法来解决PHP中使用SimpleXML处理包含CDATA段的XML文件时遇到的问题。通过设置LIBXML_NOCDATA选项,可以确保CDATA内容被正确解析为字符串。

    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

转载于:https://www.cnblogs.com/zcy_soft/archive/2011/01/14/1935312.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值