0

好的,xml文件看起来像这样,它被设置为一个变量$otherdata

<result>
 <sighting>
  <name>Johhny</name>
  <last>smith</last>
  <phone>5551234</phone>
 </sighting>
 </result>

和 php 代码看起来像这样

$dom = new DOMDocument;
$dom ->load($otherdata);
$xpath = new DomXpath($dom);

$query = '//result/sighting[name = "Johhny"]/.';
$entries = $xpath->query($query);

foreach ($entries as $entry) {
 $newlat = $entry->textContent;

 echo $newlat
 }

我遇到麻烦的地方是尝试获取“last”和“phone”属性中的值并将其设置为等于变量以稍后存储和回显...谢谢

4

2 回答 2

1

通过这种方式,您可以遍历所有瞄准元素,并在这些元素中获得所有子元素。现在您可以将所有数据存储在一个数组中并稍后显示。

$data = array();
$xml = new DOMDocument();
$xml->load($otherdata);

$nodes = $xml->getElementsByTagName('sighting');
foreach ($nodes as $node) {
    $children = $node->childNodes; 
    $i=0;
    foreach ($children as $child) { 
        $data[$i][] = $child->nodeValue;
    }
}

这样您就可以更新名称元素并保存 xml 文档。

$xml = new DOMDocument();
$xml->load($file);

$nodes = $xml->getElementsByTagName('sighting');
foreach ($nodes->item as $node) {
    $children = $node->childNodes; 
    foreach ($children as $child) { 
        if ($child->nodeName == 'name')
            $child->nodeValue = 'Not Johnny';
    } 
}

$xml->save($file);
于 2014-06-15T10:32:52.897 回答
1

你可以使用

$query = '//result/sighting[name = "Johhny"]';

作为路径,您可以直接选择sighting元素。然后你可以读出内容并改变它

foreach ($entries as $entry) {
 $last = $entry->getElementsByTagName('last')->item(0)->textContent;
 $entry->getElementsByTagName('name')->textContent = $newName;
 }
于 2014-06-15T08:42:47.310 回答