在DomXML和PHP中按属性值获取节点

时间:2013-01-09 14:10:51

标签: php xml

我正在尝试选择特定节点以便稍后编辑其内容和属性,但我无法选择notice节点(请参阅下面的PHP代码)。

XML文档

<?xml version="1.0" encoding="UTF-8"?>
<notices lastID="0001">
    <!--
    <notice id="0000" endDate="31-12-2025">
        Content of the notice.
    </notice>
    -->
    <notice id="0001" endDate="13-01-2013" active="1">
        One amazing notice.
    </notice>

</notices>

$id值为&#34; 0001&#34; (字符串)。

PHP

$document = new DOMDocument;
$document = dom_import_simplexml($this->xml);

$notices= $document->getElementsByTagName('notice');
#var_dump($notices);

foreach($notices as $element)
{
    if($element->getAttribute('id') == $id)
    {
        $notice = $element;
        var_dump($notice); //Returns absolutely nothing (I guess the if returns false).
    }
}

$notice->removeAttribute("endDate");
$notice->setAttribute("endDate",$endDate);

每次我进入if声明,我的$notice都不会返回任何值 我尝试使用xpath查询(//notice[@id="{$id}"])但没有成功。

澄清一下,我的问题是$element->getAttribute('id')似乎不起作用。


我也试过 SimpleXML

PHP

$document = new DOMDocument;
$document = simplexml_import_dom($this->xml);

$notice = "";

foreach($document->notices->children() as $element)
{
    $attributes = $element->attributes();
    if($attributes['id'] == $id)
    {
        $notice= $element;
        var_dump($notice);
    }
}
$avis->removeAttribute("endDate");
$avis->setAttribute("endDate",$endDate);

SimpleXML在以下行中给出了以下消息:Node no longer exists

foreach($document->notices->children() as $element)

1 个答案:

答案 0 :(得分:0)

我终于明白了。

<强> PHP

$document = simplexml_import_dom($this->xml);
$notice = "";

$xpathResults = $document->xpath('//notice');


foreach($xpathResults as $element)
{
    $elementID = $element->id[0];
    $domXML = dom_import_simplexml($element);

    if((string) $noticeID == $id)
    {
        $notice = $domXML;

    }
}
相关问题