You can use the SimpleXMLElement::asXML() method to accomplish this:

$string = "<element><child>Hello World</child></element>";
$xml = new SimpleXMLElement($string);

// The entire XML tree as a string:
// "<element><child>Hello World</child></element>"
$xml->asXML();

// Just the child node as a string:
// "<child>Hello World</child>"
$xml->child->asXML();
Answer from user142162 on Stack Overflow
🌐
PHP
php.net › manual › en › function.simplexml-load-string.php
PHP: simplexml_load_string - Manual
I had a hard time finding this documented, so posting it here in case it helps someone: If you want to use multiple libxml options, separate them with a pipe, like so: <?php $xml = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS); ?>
🌐
W3Schools
w3schools.com › php › func_simplexml_load_string.asp
PHP simplexml_load_string() Function
Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.
Top answer
1 of 2
3

The contents of the "string" element is an XML document itself - stored in an text node. You can consider it an envelope. So you have to load the outer XML document first and read the text content, then load it as an XML document again.

$outerXML = <<<'XML'
<?xml version="1.0" encoding="utf-8"?> 
<string xmlns="http://www.cebroker.com/CEBrokerWebService/">&lt;licensees&gt;&lt;licensee
 valid="true" State="FL" licensee_profession="RN"
 licensee_number="2676612" state_license_format="" first_name="HENRY"
 last_name="GEITER" ErrorCode="" Message="" TimeStamp="2/19/2022
 4:53:35 AM" /&gt;&lt;/licensees&gt;</string>
XML;

$envelope = new SimpleXMLElement($outerXML);
$licensees = new SimpleXMLElement((string)$envelope);

echo $licensees->asXML();

In DOM:

$envelope = new DOMDocument();
$envelope->loadXML($outerXML);
$document = new DOMDocument();
$document->loadXML($envelope->documentElement->textContent);

echo $document->saveXML();
2 of 2
2

Since the XML you want seem to be stored as htmlentities, your first simplexml_load_string() won't read it as XML. If you take that string and run that through simplexml_load_string() as well then you'll get it as XML:

$xml_string = simplexml_load_string($xmlresponse);
$licensees = simplexml_load_string($xml_string);

var_dump($licensees);

Output:

object(SimpleXMLElement)#2 (1) {
  ["licensee"]=>
  object(SimpleXMLElement)#3 (1) {
    ["@attributes"]=>
    array(10) {
      ["valid"]=>
      string(4) "true"
      ["State"]=>
      string(2) "FL"
      ["licensee_profession"]=>
      string(2) "RN"
      ["licensee_number"]=>
      string(7) "2676612"
      ["state_license_format"]=>
      string(0) ""
      ["first_name"]=>
      string(5) "HENRY"
      ["last_name"]=>
      string(6) "GEITER"
      ["ErrorCode"]=>
      string(0) ""
      ["Message"]=>
      string(0) ""
      ["TimeStamp"]=>
      string(21) "2/19/2022  4:53:35 AM"
    }
  }
}

Here's a demo: https://3v4l.org/da3Up

Top answer
1 of 4
4

htmlspecialchars is what you need. It's a lot more selective, unlike htmlentities, over what it converts.

From htmlentities documentation:

This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.

<?php
$a = "I love things & stuffë";
$b = htmlspecialchars(c = htmlentities($a);
echo "$b\n$c\n";

Outputs:

I love things &amp; stuffë
I love things &amp; stuff&Atilde;&laquo;

http://www.php.net/manual/en/function.htmlspecialchars.php

2 of 4
2

If you create XML you likely have a DOMDocument at hand already. Even if not, you can easily create one. With a DOMDocument you can create text that is 100% well-formed for XML:

$text = "I'm using php v5.3. I would like to convert a string to valid xml. Xml apparently requires '&' characters to be encoded to &amp; but all functions I can find which do this also convert characters like 'ë' to html entities xml doesn't accept (&euml; in this case). What function should I use?";

$doc = new DOMDocument();
echo $doc->saveXML($doc->createTextNode($text));

This gives you the following output (verbatim):

I'm using php v5.3. I would like to convert a string to valid xml. Xml apparently requires '&amp;' characters to be encoded to &amp;amp; but all functions I can find which do this also convert characters like 'ë' to html entities xml doesn't accept (&amp;euml; in this case). What function should I use?

🌐
GeeksforGeeks
geeksforgeeks.org › php › php-simplexml_load_string-function
PHP | simplexml_load_string() Function - GeeksforGeeks
July 11, 2025 - Below programs illustrate the simplexml_load_string() function: Program 1: ... <?php $note=<<<XML <note> <to>User 1</to> <from>User 2</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> XML; $xml = ...
Top answer
1 of 3
20

Try with simple XML, here's an example:

do.php:

<?php
$xml_str = file_get_contents('xmlfile.xml');
$xml = new SimpleXMLElement($xml_str);
$items = $xml->xpath('*/item');

foreach($items as $item) {
    echo $item['title'], ': ', $item['description'], "\n";
}

xmlfile.xml:

<?xml version="1.0" encoding="UTF-8"?>
<xml>
    <items>
        <item title="Hello World" description="Hellowing the world.." />
        <item title="Hello People" description="greeting people.." />
    </items>
</xml>
2 of 3
16

For those situations where SimpleXML is not available, I use this function originally posted in a comment on php.net. It works great 99% of the time.

<?php
/**
 * Convert XML to an Array
 *
 * @param string  $XML
 * @return array
 */
function XMLtoArray($XML)
{
    $xml_parser = xml_parser_create();
    xml_parse_into_struct($xml_parser, $XML, $vals);
    xml_parser_free($xml_parser);
    // wyznaczamy tablice z powtarzajacymi sie tagami na tym samym poziomie
    $_tmp='';
    foreach ($vals as $xml_elem) {
        $x_tag=$xml_elem['tag'];
        $x_level=$xml_elem['level'];
        $x_type=$xml_elem['type'];
        if ($x_level!=1 && $x_type == 'close') {
            if (isset($multi_key[$x_tag][$x_level]))
                $multi_key[$x_tag][$x_level]=1;
            else
                $multi_key[$x_tag][$x_level]=0;
        }
        if ($x_level!=1 && $x_type == 'complete') {
            if ($_tmp==$x_tag)
                $multi_key[$x_tag][$x_level]=1;
            $_tmp=$x_tag;
        }
    }
    // jedziemy po tablicy
    foreach ($vals as $xml_elem) {
        $x_tag=$xml_elem['tag'];
        $x_level=$xml_elem['level'];
        $x_type=$xml_elem['type'];
        if ($x_type == 'open')
            $level[$x_level] = $x_tag;
        $start_level = 1;
        $php_stmt = '$xml_array';
        if ($x_type=='close' && $x_level!=1)
            $multi_key[$x_tag][$x_level]++;
        while ($start_level < $x_level) {
            $php_stmt .= '[$level['.$start_level.']]';
            if (isset($multi_key[$level[$start_level]][$start_level]) && $multi_key[$level[$start_level]][$start_level])
                $php_stmt .= '['.($multi_key[$level[$start_level]][$start_level]-1).']';
            $start_level++;
        }
        $add='';
        if (isset($multi_key[$x_tag][$x_level]) && $multi_key[$x_tag][$x_level] && ($x_type=='open' || $x_type=='complete')) {
            if (!isset($multi_key2[$x_tag][$x_level]))
                $multi_key2[$x_tag][$x_level]=0;
            else
                $multi_key2[$x_tag][$x_level]++;
            $add='['.$multi_key2[$x_tag][$x_level].']';
        }
        if (isset($xml_elem['value']) && trim($xml_elem['value'])!='' && !array_key_exists('attributes', $xml_elem)) {
            if ($x_type == 'open')
                $php_stmt_main=$php_stmt.'[$x_type]'.$add.'[\'content\'] = $xml_elem[\'value\'];';
            else
                $php_stmt_main=$php_stmt.'[$x_tag]'.$add.' = $xml_elem[\'value\'];';
            eval($php_stmt_main);
        }
        if (array_key_exists('attributes', $xml_elem)) {
            if (isset($xml_elem['value'])) {
                $php_stmt_main=$php_stmt.'[$x_tag]'.$add.'[\'content\'] = $xml_elem[\'value\'];';
                eval($php_stmt_main);
            }
            foreach ($xml_elem['attributes'] as $key=>$value) {
                $php_stmt_att=$php_stmt.'[$x_tag]'.$add.'[$key] = $value;';
                eval($php_stmt_att);
            }
        }
    }
    return $xml_array;
}
?>
🌐
BCCNsoft
doc.bccnsoft.com › docs › php-docs-7-en › simplexmlelement.asxml.html
Return a well-formed XML string based on SimpleXML element
If the parameter is specified, it returns TRUE if the file was written successfully and FALSE otherwise. ... <?php $string = <<<XML <a> <b> <c>text</c> <c>stuff</c> </b> <d> <c>code</c> </d> </a> XML; $xml = new SimpleXMLElement($string); echo $xml->asXML(); ?>
Find elsewhere
🌐
W3Schools
w3schools.com › php › php_xml_simplexml_read.asp
PHP SimpleXML Parser
This parser provides an easy way to access elements, attributes and textual content of an XML document. Tip: The SimpleXML Parser is a part of the PHP core. No installation is required! You can read XML from a string or from a file, using these functions:
🌐
Plus2Net
plus2net.com › php_tutorial › php-xml-loadstring.php
simplexml_load_string to get an object from a XML formatted string
<?Php $str_xml = <<<XML <?xml version='1.0' standalone='yes'?> <details> <name>Abcd</name> <address> <door_no>234-ac</door_no> <street>Great Wall</street> <city>Alabama</city> </address> </details> XML; $str=simplexml_load_string($str_xml); print_r($str); ?> Output is here
🌐
Tutorialspoint
tutorialspoint.com › php › php_function_simplexml_load_string.htm
PHP simplexml_load_string() Function
The simplexml_load_string() accepts an (well-formed) XML string as a parameter converts it into an object of the SimpleXMLElement class and returns it. simplexml_load_string($data, [$class_name, $options, $ns, $is_prefix]); This function returns an object of the SimpleXMLElement class in case ...
🌐
GitHub
github.com › gaarf › XML-string-to-PHP-array
GitHub - gaarf/XML-string-to-PHP-array: One common need when working in PHP is a way to convert an XML document into a serializable array. If you ever tried to serialize() and then unserialize() a SimpleXML or DOMDocument object, you know what I’m talking about.
There’s a quick and dirty way to do convert such a document to an array, using type casting and the JSON functions to ensure there are no exotic values that would cause problems when unserializing: $a = json_decode(json_encode((array) Convertor::covertToArray($s)), true); Here is the result for our sample XML, eg if we print_r($a):
Starred by 113 users
Forked by 29 users
Languages   PHP 100.0% | PHP 100.0%