[PHP] Changes nodes' values of a XML document

Published on 2019-07-18 • Modified on 2019-07-18

I always forget how to do this! 🤔 So we will load the XML with a PHP DOMDocument object then we will retrieve the nodes to modify using a DOMXpath object. Of course there are many other ways to do this. Check out the PHP documentation.

<?php declare(strict_types=1);

namespace App\Controller\Snippet;

 * I am using a PHP trait in order to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
trait Snippet32Trait
     * Code for snippet 32.
    public function snippet32(): void
        $xml = <<<EOD
<?xml version="1.0" encoding="iso-8859-1"?>

        $dom = new \DOMDocument();
        $dom->preserveWhiteSpace = false;
        $dom->formatOutput = true;
        echo $dom->saveXML();

        // Remove values of some nodes...
        $nodes = (new \DOMXPath($dom))->query('//Login|//Birthday');
        foreach ($nodes ?: [] as $node) {
            $node->nodeValue = null;

        echo PHP_EOL.$dom->saveXML(); // That's it! 😁

 Run this snippet  More on Stackoverflow