【问题标题】:Get value from a CDATA in xml从 xml 中的 CDATA 获取值
【发布时间】:2014-04-24 19:35:51
【问题描述】:

我不知道如何从这个 xml 代码中获取 php 值中的纬度、经度:

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.1">
<Document>
<name>OpenCellID Cells</name>
<description>List of available cells</description>
<Placemark><name></name><description><![CDATA[lat: <b>3.378199</b><br/>lon:    <b>-76.523528</b><br/>mcc: <b>732</b><br/>mnc: <b>123</b><br/>lac: <b>4003</b><br/>cellid: <b>26249364</b><br/>averageSignalStrength: <b>0</b><br/>samples: <b>10</b><br/>changeable: <b>1</b>]]></description><Point><coordinates>-76.523528,3.378199,0</coordinates></Point></Placemark>
 </Document>
 </kml>

我希望你能帮我解决这个问题。谢谢

【问题讨论】:

标签: php xml cdata


【解决方案1】:

诀窍是先将 cdata 作为字符串读出,让 libxml 将其包装成 welformatted html,然后从包含数据的节点中解析出值。

请注意,这可行,但假设 lon 和 lat 始终位于 cdata 的第一个节点中

// the xml as a variable
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.1">
<Document>
<name>OpenCellID Cells</name>
<description>List of available cells</description>
<Placemark><name></name><description><![CDATA[lat: <b>3.378199</b><br/>lon:       <b>-76.523528</b><br/>mcc: <b>732</b><br/>mnc: <b>123</b><br/>lac: <b>4003</b><br/>cellid: <b>26249364</b><br/>averageSignalStrength: <b>0</b><br/>samples: <b>10</b><br/>changeable: <b>1</b>]]></description><Point><coordinates>-76.523528,3.378199,0</coordinates></Point></Placemark>
</Document>
</kml>';

// read into dom
$domdoc = new DOMDocument();

$domdoc->loadXML($xml);

// the cdata as a string 
$cdata = $docdom->getElementsByTagName('Placemark')->item(0)->getElementsByTagName('description')->item(0)->nodeValue;

// a dom object for the cdata
$htmldom = new DOMDocument();

// wrap in html and parse
$htmldom->loadHTML($cdata);

// get the <b> nodes 
$bnodes = $htmldom->getElementsByTagName('b');

// your data :) 
$lon = $bnodes->item(0)->nodeValue;
$lat = $bnodes->item(1)->nodeValue;

最后同样重要的是,这是为了说明 loadXML 和 loadHTML 的不同之处以及如何使用它们。至于googleeart kml,我相信这是一种更标准的解析方式......

【讨论】:

    猜你喜欢
    • 2021-06-15
    • 2012-04-22
    • 2014-03-05
    • 2010-12-16
    • 2020-08-27
    • 1970-01-01
    • 2014-11-22
    • 2017-07-02
    • 1970-01-01
    相关资源
    最近更新 更多