[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 load the XML with a PHP DOMDocument object then we 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 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 = <<<XML
<?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>
XML;

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

        // Remove values of some nodes...
        $nodes = (new \DOMXPath($dom))->query('//Login|//Birthday');
        if (!$nodes instanceof \DOMNodeList) {
            throw new \RuntimeException('Nodes not found.');
        }

        /** @var \DOMElement $node */
        foreach ($nodes as $node) {
            $node->nodeValue = '';
        }

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

 Run this snippet  ≪ this.showUnitTest ? this.trans.hide_unit_test : this.trans.show_unit_test ≫  More on Stackoverflow  Random snippet

  Work with me!

<?php

declare(strict_types=1);

namespace App\Tests\Integration\Controller\Snippets;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * @see Snippet32Trait
 */
final class Snippet32Test extends KernelTestCase
{
    /**
     * @see Snippet32Trait::snippet32
     */
    public function testSnippet32(): void
    {
        $xml = <<<EOD
<?xml version="1.0" encoding="iso-8859-1"?>
<data>
  <Id>12345689</Id>
  <Email>example@example.com</Email>
  <Login>MrExample</Login>
  <Birthday>1979-01-01</Birthday>
</data>
EOD;

        $nodesPath = '//Login|//Birthday';
        $dom = new \DOMDocument();
        $dom->preserveWhiteSpace = false;
        $dom->loadXML($xml);

        $nodes = (new \DOMXPath($dom))->query($nodesPath);
        if (!$nodes instanceof \DOMNodeList) {
            throw new \RuntimeException('No nodes found.');
        }

        /** @var \DOMElement $node */
        foreach ($nodes as $node) {
            self::assertNotEmpty($node->nodeValue);
        }

        /** @var \DOMElement $node */
        foreach ($nodes as $node) {
            $node->nodeValue = '';
        }

        /** @var \DOMElement $node */
        foreach ($nodes as $node) {
            self::assertEmpty($node->nodeValue);
        }
    }
}