[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 Sf 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Sf <= 4.1)
 * Services are injected in the controller constructor.
 */
trait Snippet32Trait
{
    /**
     * Code for snippet 32.
     */
    public function snippet32(): void
    {
        $xml = <<<EOD
<?xml version="1.0" encoding="iso-8859-1"?>
<data>
  <Id>123456</Id>
  <Email>example@example.com</Email>
  <Login>MrExample</Login>
  <Birthday>1979-01-01</Birthday>
</data>
EOD;

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

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

        echo PHP_EOL.$dom->saveXML();

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow