1

我正在从 XML 中提取数据,并且某些标签以这种方式在 CDATA 中包含数据

<description><![CDATA[Changes (as compared to 8.17) include:
Features:
    * Added a &#8216;Schema Optimizer&#8217; feature. Based on &#8220;procedure analyse()&#8221; it will propose alterations to data types for a table based on analysis on what data are stored in the table. The feature is available from INFO tab/HTML mode.  Refer to documentation for details.
    * A table can now be added [...]]]>
</description>

我已经在使用 preq_match 从描述标签中提取数据。那么如何从 CDATA 中提取数据?

4

3 回答 3

7

不管是哪种语言,都不要使用正则表达式来解析 XML——你几乎肯定会弄错。使用XML 解析器

于 2009-11-17T05:58:08.817 回答
0

如果您需要提取一组复杂的数据,您应该使用simple_xml 。xpath

<?php
$string = <<<XML
<?xml version='1.0'?> 
<document>
 <title>Forty What?</title>
 <from>Joe</from>
 <to>Jane</to>
 <body>
  I know that's the answer -- but what's the question?
 </body>
</document>
XML;

$xml = simplexml_load_string($string);

var_dump($xml);
?>

会提供这样的输出:

SimpleXMLElement Object
(
  [title] => Forty What?
  [from] => Joe
  [to] => Jane
  [body] =>
   I know that's the answer -- but what's the question?
)

所以在你的情况下,你只是在你的文档中导航比 reg 表达式更容易,不是吗?

于 2009-11-17T06:13:17.610 回答
0

@Pavel Minaev 将正则表达式选项作为最后的手段是正确的,对于 xml 始终使用 Xml 解析器,您现在可以在几乎所有语言中找到 xml 解析器。例如,我通常使用 DOMDocument 在 php 中解析或创建 xml。它非常简单易懂,特别适合像我这样偶尔使用 php 的人。

例如,您想从以下 xml 中提取 CDATA

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE message SYSTEM "https://www.abcd.com/dtds/AbcdefMessageXmlApi.dtd">
<message id="9002">
  <report>
    <![CDATA[id:50121515075540159 sub:001 text text text text text]]>
  </report>
  <number>353874181931</number>
</message>

使用以下代码提取 CDATA

$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;

if (TRUE != $doc->loadXML($xml_response)) {

    // log error and / or throw expection or whatever
}

$response_element = $doc->documentElement;

if($response_element->tagName ==  "message"){

    $report_node = $response_element->getElementsByTagName("report");

    if($report_node != null && $report_node->length == 1) {

        $narrative = $report_node->item(0)->textContent;

        $log->debug("CDATA: $narrative");

    } else {

        $log->error("unable to find report tag or multiple report tag found in response xml");
    }

} else {

    $log->error("unexpected root tag (" . $response_element->tagName .") in response xml");
}

这个变量执行后$narrative应该有所有的文本,不用担心它不会包含丑陋的标签部分CDATA。

快乐编码:)

于 2014-03-26T23:13:49.527 回答