Haritz
Haritz

Reputation: 1752

PHP5 and DOM changing XML node attribute value

Having the next 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>

And the next PHP code:

<?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";      
    }
}

I would like to know how to correctly write the next line of code in the PHP code:

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

It is obviously wrong written. What I would like to do is to change the "no" of markable_2 to "yes". Any idea?

Upvotes: 1

Views: 3025

Answers (2)

hakre
hakre

Reputation: 197757

Use the xpath query to directly select all attributes you'd like to change and manipulate them:

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

and done. Full example:

$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();

Upvotes: 0

kapa
kapa

Reputation: 78671

You can find this information in the documentation.

$Idaztekoa->setAttribute('atrib', 'yes');

Upvotes: 4

Related Questions