Search code examples
phpnewlinesimplexmldomdocument

Output BR tag, using simpleXML


I want to have the text string "hello there" separate in 2 lines. For this I need the simpleXML to create the "br-tag" in the output file result.xml, but I only get produced the code <br>.

<?php

// DOMDocument

$dom = new DomDocument('1.0', 'UTF-8');
$dom->formatOutput = true;

$html = $dom->appendChild($dom->createElement("html"));

$xmlns = $dom->createAttribute('xmlns');
$xmlns->value = 'http://www.w3.org/1999/xhtml';
$html->appendChild($xmlns);

// SimpleXML

$sxe = simplexml_import_dom($dom);
$head = $sxe->addChild('head', ' ');
$body = $sxe->addChild('body', 'hello <br> there');

echo $sxe->asXML('result.xml');

Result:

hello <br> there

Wanted Result:

hello

there


Solution

  • Firstly, PHP's SimpleXML extension works only with XML, not HTML. You're rightly mentioning XHTML in your setup code, but that means you need to use XML self-closing elements like <br /> not HTML unclosed tags like <br>.

    Secondly, the addChild method takes text content as its second parameter, not raw document content; so as you've seen, it will automatically escape < and > for you.

    SimpleXML is really designed around the kind of XML that's a strict tree of elements, rather than a markup language with elements interleaved with text content like XHTML, so this is probably a case where you're better off sticking to the DOM.

    Even then, there's no equivalent of the JS "innerhtml" property, I'm afraid, so I believe you'll have to add the text and br element as separate nodes, e.g.

    $body = $html->appendChild( $dom->createElement('head') );
    
    $body->appendChild( $dom->createTextNode('hello') );
    $body->appendChild( $dom->createElement('br') );
    $body->appendChild( $dom->createTextNode('world') );