gpt4 book ai didi

php - 如何从xml中使用xpath获得第二个同级

转载 作者:行者123 更新时间:2023-12-03 16:20:17 28 4
gpt4 key购买 nike

这是我的结构:

<Users>
<User>
<username>admin</username>
<server>10.xx.xx.xx</server>
<image>images/pic.png</image>
</User>
<User>
<username>bob</username>
<server>10.xx.xx.xx</server>
<image>images/pic2.png</image>
</User>
</Users>


现在,我有了这段代码,该代码从具有所需用户名的节点中获取服务器值。

$query = '//Users/User/username[. =  "'.$_SESSION['SESS_FIRST_NAME'].'"]';
$entries = $xpath->query($query);

foreach ($entries as $entry) {
//Getting the "server" node value
$server=$entry->nextSibling->nextSibling->nodeValue;
//I wanted to have one more variable here which will save me the image string in the global php variable
$images=$entry->nextSibling->nextSibling->nextSibling->nodeValue; //this is giving me a server value instead of image value
}

最佳答案

除非文档的模式明确声明,否则我将不依赖元素的顺序,而是通过将用户元素作为上下文节点传递来通过xpath查询元素(请参见示例),或者遍历用户元素的子元素并获取需要什么(例如在php数组中)。

<?php
$doc = new DOMDOcument;
$doc->loadxml( getData() );

$xpath = new DOMXPath( $doc );

$query = '/Users/User[username= "'.'bob'.'"]';
foreach( $xpath->query($query) as $user ) {
$username = singleNodeValue($xpath->query('username', $user)); // ok, you already have this one....
$server = singleNodeValue($xpath->query('server', $user));
$image = singleNodeValue($xpath->query('image', $user));

printf("%s, %s, %s\r\n", $username, $server, $image);
}

function singleNodeValue($nodeset) {
// add tests here....
return $nodeset->item(0)->nodeValue;
}

function getData() {
return <<< eox
<Users>
<User>
<username>admin</username>
<server>10.xx.xx.xx</server>
<image>images/pic.png</image>
</User>
<User>
<username>bob</username>
<server>10.xx.xx.xx</server>
<image>images/pic2.png</image>
</User>
</Users>
eox;
}


版画

bob, 10.xx.xx.xx, images/pic2.png

关于php - 如何从xml中使用xpath获得第二个同级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12560450/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com