1

I have a SimpleXMLElement made, and I want to write my own XML inside it, whenever I write the XML it returns with &lt; and other escaped characters. With XMLWriter's writeRaw function, I can write <a>a</a><b>b</b> and the XML file will include that exact string, not escaped in any way.

Is there a way I can write that string using SimpleXMLElement and have it return with the exact string, not escaped.

I have seen this question before, but the answer returns an error when I use it and I cannot seem to fix it.

Community
  • 1
  • 1
ZomoXYZ
  • 1,763
  • 21
  • 44
  • Possible duplicate of [PHP - SimpleXML - AddChild with another SimpleXMLElement](http://stackoverflow.com/questions/4778865/php-simplexml-addchild-with-another-simplexmlelement) – E_p Jan 11 '16 at 23:16
  • Deleting my answer as question is duplicate. You should think of deleting question. – E_p Jan 11 '16 at 23:18

1 Answers1

2

SimpleXML doesn't have this ability directly, but it is available in the DOM family of functions. Thankfully, it is easy to work with SimpleXML and DOM at the same time on the same XML document.

The example below uses a document fragment to add a couple of elements to a document.

<?php

$example = new SimpleXMLElement('<example/>');

// <example/> as a DOMElement
$dom = dom_import_simplexml($example);

// Create a new DOM document fragment and put it inside <example/>
$fragment = $dom->ownerDocument->createDocumentFragment();
$fragment->appendXML('<a>a</a><b>b</b>');
$dom->appendChild($fragment);

// Back to SimpleXML, it can see our document changes
echo $example->asXML();

?>

The above example outputs:

<?xml version="1.0"?>
<example><a>a</a><b>b</b></example>
salathe
  • 51,324
  • 12
  • 104
  • 132