从 XMLReader 打开的 simplexml 中的 CData [英] CData in simplexml opened from XMLReader

查看:25
本文介绍了从 XMLReader 打开的 simplexml 中的 CData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆 XML 文件,我正在使用 XMLReader 将它们加载到我的脚本中,创建 DOM 对象,然后转换为 Simplexml.

I've got a bunch of XML file which I'm loading in to my script using XMLReader, creating DOM object and then converting to Simplexml.

问题是使用 SIMPLEXML 忽略的 CDATA 的 XML 文件之一,通常使用 SIMPLEXML_LOAD_FILE 我会添加 LIBXML_NOCDATA 参数,但是当我使用 simplexml_import_dom 时,我无法弄清楚如何在下面的场景中忽略 CDATA.

Problem is one of the XML file uses CDATA which SIMPLEXML ignores and normally using SIMPLEXML_LOAD_FILE I'd add the LIBXML_NOCDATA parameter but as I'm using simplexml_import_dom I can't figure out how to ignore the CDATA in the sceanrio below.

有什么想法吗?

非常感谢布雷特

$file = 'test.xml';
$reader = new XMLReader();
$reader->open($file);       
while ($reader->read())
{
    // are we in a product?
    if ($reader->nodeType == XMLReader::ELEMENT &&
        strtolower($reader->localName) == 'product')

    {
        if (!$node = $reader->expand()) {
            //do nothing 
        }
        else {
             // expand the node into a DOMNode
        // Convert to SimpleXML via DOM, messy but SimpleXML is soo much nicer.
        $dom  = new DomDocument();
        $dom->appendChild($dom->importNode($node, true));
        $products = simplexml_import_dom($dom);

        // do whatever we want to do with the product data

}

推荐答案

您可以尝试以下操作:

<?php
$str = $dom->saveXML();
$product = simplexml_load_string($str, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS);

这篇关于从 XMLReader 打开的 simplexml 中的 CData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆