1

我想从远程位置的 xml 文件中获取数据,该文件包含所有节点中的 CDATA 信息,如下所示。我使用以下 PHP 函数来获取此类信息,但它不起作用并且似乎无法从 xml 文件中捕获 CDATA 标记。问题是我的代码是否正确?如果它错了,你能建议任何 php 代码来获取请求的信息吗?

<Items>
      <Item ID="1">
          <Name>Mountain</Name>
          <Properties>
              <Property Code="feature"><![CDATA[<ul><li>sample text</li></ul>]]></Property>
              <Property Code="SystemRequirements"><![CDATA[Windows XP/Windows Vista]]></Property>
              <Property Code="Description" Type="plain"><![CDATA[sample text2]]></Property>
          </Properties>
      </Item>
<Items>

这是我的 php 代码:

  <?
    function xmlParse($file, $wrapperName, $callback, $limit = NULL) {
        $xml = new XMLReader();
        if (!$xml->open($file)) {
            die("Failed to open input file.");
        }
        $n = 0;
        $x = 0;
        while ($xml->read()) {
            if ($xml->nodeType == XMLReader::ELEMENT && $xml->name == $wrapperName) {
                while ($xml->read() && $xml->name != $wrapperName) {
                    if ($xml->nodeType == XMLReader::ELEMENT) {
                        //$subarray[]=$xml->expand();
                        $doc = new DOMDocument('1.0', 'UTF-8');
                        $simplexml = simplexml_import_dom($doc->importNode($xml->expand(), true));
                        $subarray[]=$simplexml;
                    }
                }
                if ($limit == NULL || $x < $limit) {
                    if ($callback($subarray)) {
                        $x++;
                    }
                    unset($subarray);
                }
                $n++;
            }
        }
        $xml->close();
    }

    echo '<pre>';

    function func1($s) {
        print_r($s);
    }

    xmlParse('myfile.xml', 'Item', 'func1', 100);

当我通过 print_r($s); 打印这个对象时 我在结果中看不到 CDATA !您有什么想法可以检索 CDATA 上下文吗?

4

2 回答 2

1

把它当作一个字符串

$file = "1.xml";
$xml = simplexml_load_file($file);
foreach($xml->Item->Properties->children() as $properties) {
    printf("%s", $properties);
}

输出

<ul><li>sample text</li></ul>
Windows XP/Windows Vista
sample text2
于 2013-06-22T10:17:24.173 回答
0

总有办法使用 DOMDocument 打开 xml 文件,例如:

$xmlFile = new DOMDocument();
$xmlFile->load(myfile.xml);
echo $xmlFile->getElementsByTagName('Property')->item(0)->nodeValue;
于 2013-06-22T10:14:13.353 回答