ZomoXYZ
ZomoXYZ

Reputation: 1852

Write raw xml in a SimpleXMLElement

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.

Upvotes: 1

Views: 987

Answers (1)

salathe
salathe

Reputation: 51950

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>

Upvotes: 2

Related Questions