PHP5和DOM更改XML节点属性值

时间:2012-04-24 12:14:21

标签: php xml dom domdocument

拥有下一个XML(Idatzi.xml):

<?xml version='1.0' encoding='ISO-8859-1'?>
<!DOCTYPE markables SYSTEM "markables.dtd">
<markables>
<markable id="markable_1" atrib="yes" span="word_1..word_4"> </markable>
<markable id="markable_2" atrib="no" span="word_6..word_7"> </markable>
<markable id="markable_3" atrib="yes" span="word_10..word_24"> </markable>
</markables>

下一个PHP代码:

<?php

$xmlIdatziDok = new DOMDocument();
if($xmlIdatziDok->load("Idatzi.xml") === FALSE){die('Error');}
$xPath_IdatziDok = new DOMXPath($xmlIdatziDok);

foreach ($xPath_IdatziDok->query('//markables/markable') AS $Idaztekoa)
{
  $IdaztekoaID = $Idaztekoa->getAttribute('id');
  $IdaztekoaAtrib = $Idaztekoa->getAttribute('atrib');

    if($IdaztekoaAtrib != "yes")
    {
      $Idazteko->Attribute('atrib') = "yes";      
    }
}

我想知道如何在PHP代码中正确编写下一行代码:

$Idazteko->Attribute('atrib') = "yes";

显然写错了。我想要做的是将markable_2的“否”改为“是”。有什么想法吗?

2 个答案:

答案 0 :(得分:4)

您可以在documentation

中找到此信息
$Idaztekoa->setAttribute('atrib', 'yes');

答案 1 :(得分:0)

使用xpath查询直接选择您想要更改和操作它们的所有属性:

foreach($xp->query('/markables/markable/@atrib[. != "yes"]') as $attrib)
{
    $attrib->nodeValue = 'yes';
}

并完成了。完整的例子:

$xml = <<<XML
<?xml version='1.0' encoding='ISO-8859-1'?>
<!DOCTYPE markables SYSTEM "markables.dtd">
<markables>
    <markable id="markable_1" atrib="yes" span="word_1..word_4"> </markable>
    <markable id="markable_2" atrib="no" span="word_6..word_7"> </markable>
    <markable id="markable_3" atrib="yes" span="word_10..word_24"> </markable>
</markables>
XML;

$doc = new DOMDocument();
$doc->loadXML($xml);
$xp = new DOMXPath($doc);

foreach($xp->query('/markables/markable/@atrib[. != "yes"]') as $attrib)
{
    $attrib->nodeValue = 'yes';
}

echo $doc->saveXML();