简体   繁体   中英

Get value from a CDATA in xml

I dont know how get a lat, lon in php values from this xml code:

<?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>

I hope you can help me with this. Thanks

The trick is to read out the cdata as a string first, let libxml wrap it into welformatted html and then parse out the values from the nodes containing your data.

Note that this works but assumes that lon and lat are always in the first nodes in the 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;

Last not least, this is to illustrate how loadXML and loadHTML differ and how to use that. As for googleeart kml, I am sure that is a more standard way to parse ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM