好的,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'属性中的值并将其设置为等于变量以便稍后存储和回显...谢谢
答案 0 :(得分:1)
您可以使用
$query = '//result/sighting[name = "Johhny"]';
作为路径,您直接选择sighting
元素。然后你可以读出内容并用
foreach ($entries as $entry) {
$last = $entry->getElementsByTagName('last')->item(0)->textContent;
$entry->getElementsByTagName('name')->textContent = $newName;
}
答案 1 :(得分: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);