Heim >Backend-Entwicklung >PHP-Tutorial >XML节点提取问题

XML节点提取问题

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-06 20:18:251425Durchsuche

现有的PHP代码输出XML节点时,只能输出第一个同名节点内容"100". 请问怎样才能输出所有节点的内容呢?

现有代码见下:
/* $xmlstring 原内容:
**

-
id*cn
100
101
102
103
105
**
*/

$xmldoc = new DOMDocument();
$xmldoc->loadXML($xmlstring);
$users = $xmldoc->getElementsByTagName('GetUserInfo');
foreach ($users as $user) {
$html .= 'outputCustomer:'.get_txt($user,'Customer').'
';
$html .= 'outputGeo:'.get_txt($user,'GeocallCLI').'
';
}
echo $html;

function get_txt($parent, $name) {
$nodes = $parent->getElementsByTagName($name);
return $nodes->item(0)->nodeValue;
}
?>

回复内容:

现有的PHP代码输出XML节点时,只能输出第一个同名节点内容"100". 请问怎样才能输出所有节点的内容呢?

现有代码见下:
/* $xmlstring 原内容:
**

-
id*cn
100
101
102
103
105
**
*/

$xmldoc = new DOMDocument();
$xmldoc->loadXML($xmlstring);
$users = $xmldoc->getElementsByTagName('GetUserInfo');
foreach ($users as $user) {
$html .= 'outputCustomer:'.get_txt($user,'Customer').'
';
$html .= 'outputGeo:'.get_txt($user,'GeocallCLI').'
';
}
echo $html;

function get_txt($parent, $name) {
$nodes = $parent->getElementsByTagName($name);
return $nodes->item(0)->nodeValue;
}
?>

最后一行代码

<code>return $nodes->item(0)->nodeValue;</code>

因为只返回item(0)
所以只看得到一个100
只需检测$nodes的长度,循环输出即可
代码

<code><?php $xmlstring = '<?xml version="1.0"?>

<getuserinfo>
<customer>id*cn</customer>
<geocallcli>100</geocallcli>
<geocallcli>101</geocallcli>
<geocallcli>102</geocallcli>
<geocallcli>103</geocallcli>
<geocallcli>105</geocallcli>
</getuserinfo>';

$xmldoc = new DOMDocument();
$xmldoc->loadXML($xmlstring);
$users = $xmldoc->getElementsByTagName('GetUserInfo');
$html  = '';
foreach ($users as $user) {
    $html .= get_txt($user, 'Customer') . '
';
    $html .= get_txt($user, 'GeocallCLI') . '
';
}
echo $html;

function get_txt($parent, $name)
{
    $nodes = $parent->getElementsByTagName($name);
    
    $data = '';
    for ($i = 0; $i length; $i++) {
        $data .= 'output' . $name . ':' . $nodes->item($i)->nodeValue . '<br>';
    }
    return $data;
}
?></code>

可否代码示例,谢谢!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn