Hi All,

I am new to Drupal and PHP code, I found in Drupal 7, SimpleXMLElement is used like this:

$xml = new SimpleXMLElement($result);
      return $this->xml2array($xml);

function xml2array($xmlObject, $out = array()) {
    foreach ((array) $xmlObject as $index => $node) {
      $out[$index] = (is_object($node)) ? $this->xml2array($node) : $node;
    }

    return $out;
  }

And it can be used without any import "use" in the beginning of the php code, so there was a PHP Fatal error: Class 'Drupal\xxxx\SimpleXMLElement' not found error, while in Drupal 8, I added the import "use Symfony\Component\DependencyInjection\SimpleXMLElement;" and this error is gone, but the same code cannot work as as in Drupal 7. Can anyone advise how to use this object as in Drupal 7's code, or is there any other replacement for it?

Thanks in advance.

Comments

jay_sitlani’s picture

Hope this will be helpful to you

Step-1:- XMl String

$data = "";
		$data .= '<?xml version="1.0" encoding="utf-8"?>
		<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="xxxxxxxx">
  			<soap:Body>
    			<client_login xmlns="xxxxxxxxx">
      				<Email>xxxxx</Email>
      				<Password>xxxxx</Password>
      				<WebId>xxxx</WebId>
    			</client_login>
  			</soap:Body>
		</soap:Envelope>';

Step-2:- For XMl Object

	$xml = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $xml);
  		$xml = simplexml_load_string($xml);

Step-3:- For array

	$json = json_encode($xml);
		$responseArray = json_decode($json,true);
  		print_r($responseArray);
  		die();

Note:- SimpleXML seems to have problems with the colon ":" in the response tags, so take them out
using preg_replace().

DigantDj’s picture

Thanks, this works!

elisur’s picture

It worked for me. Thank you very much!

parth.kukadiya’s picture

Useful. Thanks !!