Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 获取元素节点等于字符串的xml结果_Php_Xpath_Xpathquery - Fatal编程技术网

Php 获取元素节点等于字符串的xml结果

Php 获取元素节点等于字符串的xml结果,php,xpath,xpathquery,Php,Xpath,Xpathquery,好的,xml文件如下所示,它被设置为一个变量$otherdata <result> <sighting> <name>Johhny</name> <last>smith</last> <phone>5551234</phone> </sighting> </result> 我遇到的麻烦是试图获取“last”和“phone”属性中的值,并将其设置为变量,以便以

好的,xml文件如下所示,它被设置为一个变量$otherdata

<result>
 <sighting>
  <name>Johhny</name>
  <last>smith</last>
  <phone>5551234</phone>
 </sighting>
 </result>
我遇到的麻烦是试图获取“last”和“phone”属性中的值,并将其设置为变量,以便以后存储和回显…谢谢您可以使用

$query = '//result/sighting[name = "Johhny"]';
作为路径,您可以直接选择
瞄准
元素。然后你可以读出内容并用

foreach ($entries as $entry) {
 $last = $entry->getElementsByTagName('last')->item(0)->textContent;
 $entry->getElementsByTagName('name')->textContent = $newName;
 }

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

$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;
    }
}
通过这种方式,您可以更新name元素并保存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);

感谢您的快速回复,不幸的是,我需要获得多个元素…我没有在同一代码中列出它们…如果有人对如何用变量替换“Johnny”有任何想法,这将是一个额外的收获,这将非常有帮助
$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);