simplexml_load_string and simplexml_load_file are buggy and don't work well on XML with a complex markup. I tried both functions to parse some VALID XML SOAP responses and could not even get an error message. I had to use DOMDocument instead (worked like a charm).

Here is how we suppose to check simplexml for errors (if you are lucky to see errors, not just "false" returned from function)

libxml_use_internal_errors(true);
$xml=simplexml_load_string($myXMLData); //or simplexml_load_file

foreach( libxml_get_errors() as $error ) {

    print_r($error);

}
Answer from vitaly goji on Stack Overflow
🌐
PHP
php.net › manual › en › function.simplexml-load-string.php
PHP: simplexml_load_string - Manual
It doesn't seem to be documented anywhere, but you can refer to an element "value" for the purpose of changing it like so: <?php $xml = simplexml_load_string('<root><number>1</number></root>'); echo $xml->asXml(). "\n\n"; $xml->number->{0} = $xml->number->{0} + 1; echo $xml->asXml(); ?> echos: <?xml version="1.0"?> <root><number>1</number></root> <?xml version="1.0"?> <root><number>2</number></root> However, this only works with a direct assignment, not with any of the other operators: <?php $xml = simplexml_load_string('<root><number>1</number></root>'); echo $xml->asXml().
Discussions

xml - PHP: Call to undefined function: simplexml_load_string() - Stack Overflow
i followed the same : still i get ... simplexml_load_string() in /var/www/html/magento1901/lib/Varien/Simplexml/Config.php on line 510 2016-10-26T06:16:01.52Z+00:00 ... I had received a unrecognized service error. I just restarted apache2 and this fixed this issue. Thaks for the help find this line in PHP.ini 2016-10-28T17:28:19.203Z+00:00 ... yep, this worked, and I was able to skip the first step as @wmfrancia stated. 2016-12-24T20:02:18.193Z+00:00 ... If the XML module is not installed, ... More on stackoverflow.com
🌐 stackoverflow.com
simplexml_load_string function not loading XML file in PHP - Stack Overflow
The XML returns fine but I am unable to get load using PHP's simple_xml_load_string or new SimpleXMLElement to correctly load the XML so that I can use the data as an object. More on stackoverflow.com
🌐 stackoverflow.com
The simplexml_load_string command in the php file does not work
The simplexml_load_string command in the php file does not work. Can you help me even though I have php plugins installed? simplexml_load_string command does not clear html command lines from xml file. It works smoothly on other servers without any problems. More on forum.virtualmin.com
🌐 forum.virtualmin.com
0
0
September 26, 2023
php - Issue with simplexml_load_string() - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I am trying to use an API . In this regard I am facing an issue with simplexml_load_string(). More on stackoverflow.com
🌐 stackoverflow.com
🌐
W3Schools
w3schools.com › php › func_simplexml_load_string.asp
PHP simplexml_load_string() Function
Convert an XML string into an object, then output keys and elements of the object: <?php $note=<<<XML <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Do not forget me this weekend!</body> </note> XML; $xml=simplexml_load_string($note); print_r($xml); ?> Run Example » ·
🌐
Virtualmin
forum.virtualmin.com › t › the-simplexml-load-string-command-in-the-php-file-does-not-work › 122811
The simplexml_load_string command in the php file does not work - Virtualmin - Virtualmin Community
September 26, 2023 - The simplexml_load_string command in the php file does not work. Can you help me even though I have php plugins installed? simplexml_load_string command does not clear html command lines from xml file. It works smoothly on other servers without any problems.
🌐
Stack Overflow
stackoverflow.com › questions › 31626099 › issue-with-simplexml-load-string
php - Issue with simplexml_load_string() - Stack Overflow
ErrorException (E_UNKNOWN) simplexml_load_string(): Entity: line 2: parser error : Extra content at the end of the document ... Debug the contents of the $output variable. The error message says that it isn't valid XML. ... You do not do any error detection / handling whatsoever.
Find elsewhere
🌐
OnlinePHP
onlinephp.io › simplexml-load-string › manual
simplexml_load_string - OnlinePHP.io Example
simplexml_load_string( string$data, [string|null$class_name = SimpleXMLElement::class], [int$options = 0], [string$namespace_or_prefix = ""], [bool$is_prefix = false] ): SimpleXMLElement|false
Top answer
1 of 3
7

To answer your question, let's first examine the problem.

Problem

Assuming you are displaying the contents of your $xml variable through:

php > print_r($xml);

Here, you are listing the children of the current node (the root node) with the default namespace (without prefix) which is not declared in that node:

 <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://www.beautyfort.com/api/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

If you would list the namespaces of that node:

php > print_r($xml->getNamespaces());
Array
(
    [SOAP-ENV] => http://schemas.xmlsoap.org/soap/envelope/
)

there is only a single one visible, because that is the only one actually used in that (root) node excluding its children.

To list all used namespaces of the root and all its children add 'true' as first argument:

php > print_r($xml->getNamespaces(true));
Array
(
    [SOAP-ENV] => http://schemas.xmlsoap.org/soap/envelope/
    [ns1] => http://www.beautyfort.com/api/
    [xsi] => http://www.w3.org/2001/XMLSchema-instance
)

To list all declared namespaces of the root and all its children:

php > print_r($xml->getDocNamespaces(true));
Array
(
    [SOAP-ENV] => http://schemas.xmlsoap.org/soap/envelope/
    [ns1] => http://www.beautyfort.com/api/
    [xsi] => http://www.w3.org/2001/XMLSchema-instance
)

Solution #1

simplexml_load_string allows to set a default namespace as argument, e.g. SOAP-ENV (with extra argument to indicate that it is a prefix):

php > $xml = simplexml_load_string($content, "SimpleXMLElement", 0, "SOAP-ENV", true);

If you now print your variable, you will get closer to what you need:

php > print_r($xml);
SimpleXMLElement Object
(
    [Body] => SimpleXMLElement Object
        (
        )

)

But this only holds for the root node.

When listing children, you still need to specify a namespace if the children use namespaces other than the default (empty) one, and indicate whether its a prefix or namespace:

php > print_r($xml->children("SOAP-ENV", true));
SimpleXMLElement Object
(
    [Body] => SimpleXMLElement Object
        (
        )

)

To see the children of the first root child do the following:

php > print_r($xml->children("SOAP-ENV", true)->children("ns1", true));
SimpleXMLElement Object
(
    [ProductSearchResponse] => SimpleXMLElement Object
        (
            ...
        )

)

But this might not be what you are looking for, as it is not a generic solution.

Solution #2

Use a string replace for all your namespaces and reload the XML document (stored in $content):

php > $content2 = str_replace(array_map(function($e) { return "$e:"; }, array_keys($xml->getDocNamespaces())), array(), $content);

Your input XML now looks like this:

php > echo $content2;
<?xml version="1.0" encoding="UTF-8"?><Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://www.beautyfort.com/api/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><Body><ProductSearchResponse><TestMode>false</TestMode><Page>1</Page><ResultsPerPage>1</ResultsPerPage><TotalResults>1276</TotalResults><Items><Item><StockCode>L3720</StockCode><Name>David Beckham Instinct Gift Set 30ml EDT + 150ml Shower Gel</Name><QuantityAvailable>1</QuantityAvailable><UnitPrice Currency="GBP"><Amount>8.72</Amount></UnitPrice><YourRating nil="true"/><YourStockCode></YourStockCode><ImageLastUpdated>2016-12-22 18:13:08</ImageLastUpdated><ThumbnailImageUrl>https://www.beautyfort.com/pic/Y0NqeTBJbmdvaUx6ZUFOa0MyTlNObmhGckltYnVQQmg%3D</ThumbnailImageUrl><HighResImageUrl nil="true"/></Item></Items></ProductSearchResponse></Body></Envelope>

Reload and print:

php > $xml2 = simplexml_load_string($content2);
php > print_r($xml2);
SimpleXMLElement Object
(
    [Body] => SimpleXMLElement Object
        (
            [ProductSearchResponse] => SimpleXMLElement Object
                (
                    ...
                )

        )

)
2 of 3
0

The output your getting is just not helpful more than incorrect. When dealing with SimpleXML and DOMDocument, there structure is quite complex and you don't always get all the information.

When using SimpleXML - the best way of seeing the content of a node is to use asXML(), which recreates the original XML of the node.

$xml = simplexml_load_string($response);

echo $xml->asXML();

This give you your original content.

🌐
SitePoint
sitepoint.com › php
Simplexml_load_file not working for me - PHP - SitePoint Forums | Web Development & Design Community
February 5, 2019 - Hi, I am trying to read an XML file and it returns “failed to load”. Please let me know what mistake I am making here. Its a pure simple program. I did it from localhost and with my public host, the XML file and the PHP…
🌐
Narkive
php-general.php.narkive.com › 9DTk7CQZ › issues-with-simplexml-load-string
Issues with simplexml_load_string()
When not using LIBXML_NOCDATA: echo '<pre>' . print_r( json_decode( json_encode( (array)simplexml_load_string( $previewString, 'SimpleXMLElement', LIBXML_NOBLANKS )), 1 ), TRUE ) . '</pre>'; yields the following output : Array ( [message] => Array ( ) [buttons] => Array ( [button] => Array ( [@attributes] => Array ( [name] => Add Me ) ) ) ) I get the attributes but not the CDATA. Looking at the doc page for simplexml_load_string() (http://us.php.net/manual/en/function.simplexml-load-string.php and http://us.php.net/manual/en/libxml.constants.php), I don't see a way to get access to both.
🌐
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.
🌐
WPML
wpml.org › home › errata › php 7: possible issues with simplexml
PHP 7: possible issues with simplexml - WPML
April 17, 2018 - This worked for me. ... Sometimes You must restart (if You have in Your PHP instalation) an FPM, in my situation: service php7.1-fpm restart Without this restart, I have a “Call to undefined function simplexml_load_file” although php7.1-xml was correctly installed and enabled (… from phpinfo() ) ... Thank you for the additional information! ... Amazing! Life saver! ... This did not work for me 🙁 nor did restarting php.
🌐
GitHub
github.com › php › php-src › blob › master › ext › simplexml › simplexml.c
php-src/ext/simplexml/simplexml.c at master · php/php-src
php_libxml_increment_node_ptr((php_libxml_node_object *)sxe, xmlDocGetRootElement(docp), NULL); · RETURN_OBJ(&sxe->zo); } /* }}} */ · /* {{{ Load a string and return a simplexml_element object to allow for processing */ PHP_FUNCTION(simplexml_load_string) { php_sxe_object *sxe; char *data; size_t data_len; xmlDocPtr docp; zend_string *ns = zend_empty_string; zend_long options = 0; zend_class_entry *ce= ce_SimpleXMLElement; zend_function *fptr_count; bool isprefix = false; ·
Author   php