php - XML节点提取问题
高洛峰
高洛峰 2017-04-10 16:47:32
0
2
375

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

现有代码见下:
<?php
/* $xmlstring 原内容:
**<?xml version="1.0"?>
<!DOCTYPE GetUserInfo>
-<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');
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;
}
?>

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
左手右手慢动作

最后一行代码

return $nodes->item(0)->nodeValue;

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

<?php
$xmlstring = '<?xml version="1.0"?>
<!DOCTYPE GetUserInfo>
<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 < $nodes->length; $i++) {
        $data .= 'output' . $name . ':' . $nodes->item($i)->nodeValue . '<br/>';
    }
    return $data;
}
?>
巴扎黑

可否代码示例,谢谢!

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!