简体   繁体   中英

Is it possible to change a xml variable by only its tag name with simplexml in php

I know I can set a variable like that $xml->path->to->tag = $newValue . But what if I have only tag name and don't know its path, I wonder how I can set its variable? is it possible?

You are looking for

The XPath to search for an element anywhere in the XML document is //elementName

Example XML:

<foo>
    <bar>
        <baz bam="boom">baddam</baz>
    </bar>
</foo>

Example PHP Code:

$foo = simplexml_load_string($xml);
$allBazElements = $foo->xpath('//baz');
echo
    $allBazElements[0],        // baddam
    $allBazElements[0]['bam'], // boom
    PHP_EOL;

$allBazElements[0][0] = 'changed';
$allBazElements[0]['bam'] = 'changed too';

echo $foo->asXml();

will output ( demo )

baddamboom
<?xml version="1.0"?>
<foo>
    <bar>
        <baz bam="changed too">changed</baz>
    </bar>
</foo>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM