从xml中的CDATA获取值

时间:2014-04-24 19:35:51

标签: php xml cdata

我不知道如何从这个xml代码获取一个lat,lon的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>

我希望你能帮助我。谢谢

1 个答案:

答案 0 :(得分:0)

诀窍是首先将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,我确信这是一种更标准的解析方式......