使用XML PHP,提取2节点一个阵列 [英] php with xml, extract 2 nodes to one array

查看:112
本文介绍了使用XML PHP,提取2节点一个阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些帮助,下面code,
我需要提取XML文件中2个节点,并把它们结合到一个阵列,
这里是我的code:

I need some help with the following code, I need to extract 2 nodes from XML file , and combine them to one array, here's my code :

$xml = file_get_contents('myKML.kml');
$dom = new DOMDocument;
$dom->loadXML($xml);
$coordi = $dom->getElementsByTagName('coordinates');

$coords = array();
foreach ($coordi as $coordinates) {
    $args = explode(",", $coordinates->nodeValue);
    $coords[] = array($args[0], $args[1], $args[2]);
}

print_r($coords);

现在我需要添加 $地方= $ dom->的getElementsByTagName('名');

所以输出数组应该是这个样子:

so the output array should look something like:

[名称,coordinate1,coordinate2],[名字,coordinate1,coordinate2],[名字,coordinate1,coordinate2]

[name,coordinate1,coordinate2], [name,coordinate1,coordinate2], [name,coordinate1,coordinate2]

推荐答案

使用XPath首先查询标,获取名称和接下来的每一个地标坐标。下面是使用的例子KML从维基百科

Use Xpath to query the Placemarks first, fetch the name and coordinates for each Placemark next. Here is some source using the example KML from Wikipedia

$xml = <<<'XML'
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<Placemark>
  <name>New York City</name>
  <description>New York City</description>
  <Point>
    <coordinates>-74.006393,40.714172,0</coordinates>
  </Point>
</Placemark>
</Document>
</kml>
XML;

$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);
$xpath->registerNamespace('kml', 'http://www.opengis.net/kml/2.2');

$result = array();
$places = $xpath->evaluate('//kml:Placemark', NULL, FALSE);
foreach ($places as $place) {
  $result = array(
    'name' => $xpath->evaluate('string(kml:name)', $place, FALSE),
    'coords' => explode(
      ',', 
      $xpath->evaluate('string(kml:Point/kml:coordinates)', $place, FALSE),
      3
    )
  );
}

var_dump($result);

输出:

array(2) {
  ["name"]=>
  string(13) "New York City"
  ["coords"]=>
  array(3) {
    [0]=>
    string(10) "-74.006393"
    [1]=>
    string(9) "40.714172"
    [2]=>
    string(1) "0"
  }
}

这篇关于使用XML PHP,提取2节点一个阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆