php如何查找给定节点的所有子节点

时间:2016-03-03 09:33:59

标签: php xml

我的XML输入是这样的:

<Configuaration>
    <Allowances>
        <payhead>
            <code>123</code>
            <name_en>Basic</name_en>
            <source>anything</source>
        </payhead>
    </Allowances>
    <Deductions>
        <payhead>
            <code>444</code>
            <name_en>House Rent</name_en>
            <source>anything</source>
        </payhead>
    </Deductions>
</Configuaration>

我想要的是,在我的php函数中,我将给出2个参数。第一个是输入xml,第二个是searchTag(此标记下的所有子节点都应该返回)。

我的php功能:

<?php
class myXMLUtil
{
    public static function getValue($inputXML, $searchTag)
    {
        $dom = new DOMDocument;
        $dom->loadXML($inputXML);
        $childs = $dom->getElementsByTagName($searchTag);
        foreach ($childs as $child) {
            echo '<'.$child->nodeName.'>'.$child->nodeValue.'</'.$child->nodeName.'>'.PHP_EOL;
        }
    }
}
?>  

所以,如果我把the_xml_string和&#39; payhead&#39;作为函数参数,它应该返回

<payhead>  
    <code>123</code>  
    <name_en>Basic</name_en>  
    <source>anything</source>  
</payhead>  
<payhead>  
    <code>123</code>  
    <name_en>Basic</name_en>  
    <source>anything</source>  
</payhead>  

但我得到了

<payhead>123Basicanything</payhead>  
<payhead>444House Rentanything</payhead>  

我不明白。有人可以帮忙吗?如果我的代码有问题,那么我该如何实现呢? TIA。

1 个答案:

答案 0 :(得分:2)

看起来你需要这个功能:

class myXMLUtil
{
    public static function getValue($inputXML, $searchTag)
    {
        $dom = new DOMDocument;
        $dom->loadXML($inputXML);
        $foundElements = $dom->getElementsByTagName($searchTag);
        foreach ($foundElements as $foundElement) {
            echo $foundElement->ownerDocument->saveXML($foundElement);
        }
    }
}

您可以在本地运行此代码:

<?php
$xml = <<<EOF
<Configuaration>
<Allowances>
    <payhead>
        <code>123</code>
        <name_en>Basic</name_en>
        <source>anything</source>
    </payhead>
</Allowances>
<Deductions>
    <payhead>
        <code>444</code>
        <name_en>House Rent</name_en>
        <source>anything</source>
    </payhead>
</Deductions>
</Configuaration>
EOF;
class myXMLUtil
{
    public static function getValue($inputXML, $searchTag)
    {
        $dom = new DOMDocument;
        $dom->loadXML($inputXML);
        $foundElements = $dom->getElementsByTagName($searchTag);
                foreach ($foundElements as $foundElement) {
                        echo $foundElement->ownerDocument->saveXML($foundElement);
                }
    }
}
myXMLUtil::getValue($xml, 'payhead');
?>

它将返回

<payhead>
    <code>123</code>
    <name_en>Basic</name_en>
    <source>anything</source>
</payhead><payhead>
    <code>444</code>
    <name_en>House Rent</name_en>
    <source>anything</source>
</payhead>