Search code examples
phpsimplexml

How to modify a XML node by attribute


$xmlStr = '<?xml version="1.0" encoding="utf-8"?>
<players>
    <string name="Paul">Foo</string>
    <string name="Peter">Bar</string>
</players>';

$xml = new SimpleXML($xmlStr);

How can I change Foo to Baobab in the SimpleXML object (without using a PHP loop) ?


Solution

  • When you use XPath as you say it returns an array. As this is the first item you want to change you use [0].

    To update the value, you have to get SimpleXML to know you want to set the value of the element, the simplest way of doing this is to use (in this case) is $foo[0]. Although $foo isn't an array, it fools SimpleXML into setting the value of the element rather than assigning a value to the variable called $foo.

    $xmlStr = '<?xml version="1.0" encoding="utf-8"?>
    <players>
        <string name="Paul">Foo</string>
        <string name="Peter">Bar</string>
    </players>';
    
    $xml = new SimpleXMLElement($xmlStr);
    $foo = $xml->xpath('//string[@name="Paul"]')[0];
    $foo[0] = 'Baobab';
    echo $xml->asXML();
    

    If you knew this was always going to be the layout of the XML, you could just do...

    $xml->string[0] = 'Baobab';