2

这是我的结构:

<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 
}
4

1 回答 1

2

除非文档的架构明确说明,否则我不会依赖元素的顺序,而是通过将用户元素作为上下文节点传递来通过 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
于 2012-09-24T07:40:21.910 回答