0

I am trying to append a child element to XML node

$rel->appendChild($domtree->createElement('title',NULL));

I want it to output like this

<title></title>

But I got this instead

<title/>

How to create this with an empty value ?

2

2 Answers 2

4

You need to explicitly add an empty text node:

$title = $domtree->createElement('title');
$title->appendChild($domtree->createTextNode(''));
$rel->appendChild($title);

The second argument to createElement() is non-standard and I personally don't use it, because it can produce slightly unintuitive behaviour like this.

You should always create text nodes explicitly in my opinion. Another reason for doing this is that text nodes automatically handle escaping correctly, unlike the non-standard second argument which requires that you manually escape the text data.

Sign up to request clarification or add additional context in comments.

Comments

0

For future reference, here's how you can easily build your xml from array (including empty elements):

class Test {
    public function getTestXml()
    {
        $testElements = [
            'foo' => 'foo',
            'bar' => 'bar',
            'baz' => [
                'empty' => null,
            ],
        ];

        $xml = new \DOMDocument('1.0', 'UTF-8');
        $test = $this->buildXmlNodeFromArray($xml, 'test', $testElements);

        $xml->appendChild($test);

        return $xml->saveXml();
    }

    /* Here's where all the magic happens */
    private function buildXmlNodeFromArray(\DOMDocument $document, $nodeName, array $nodeElements)
    {
        $node = $document->createElement($nodeName);

        foreach ($nodeElements as $key => $value) {
            if (null === $value || '' === $value) {
                $emptyValue = $document->createTextNode('');
                $emptyElement = $document->createElement($key);
                $emptyElement->appendChild($emptyValue);

                $node->appendChild($emptyElement);
            } elseif (is_array($value)) {
                $subNode = $this->buildXmlNodeFromArray($document, $key, $value);

                $node->appendChild($subNode);
            } else {
                $node->appendChild($document->createElement($key, $value));
            }
        }

        return $node;
    }
}

$test = new Test();

echo $test->getTestXml();

Result:

<?xml version="1.0" encoding="UTF-8"?>
<test>
    <foo>foo</foo>
    <bar>bar</bar>
    <baz>
       <empty></empty>
    </baz>
</test>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.