Unable to convert soap response string to xml in Yii2

Related searches

I have a soap request. I am able to send the request and get a response in a string. Now I want to convert it into XML and get the required data from it.

Response

string(1383) "
<?xml version="1.0" encoding="UTF-8"?>
<ResponseMessage xmlns:ns="http://iec.ch/TC57/2011/schema/message" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://iec.ch/TC57/2011/schema/message Message.xsd">
<Header>
    <Verb>reply</Verb>
    <Noun>EndDeviceControls</Noun>
    <Revision>2.0</Revision>
    <Timestamp>2019-05-04T10:39:11+04:30</Timestamp>
    <Source>HES-BSTC</Source>
    <AsyncReplyFlag>true</AsyncReplyFlag>
    <ReplyAddress>http://ip:port/AmiWeb/services/Metering</ReplyAddress>
    <User>
        <UserID>user</UserID>
    </User>
    <MessageID>6C3F761B-A1EC-4EBE-BB49-67B720C5AE62</MessageID>
    <CorrelationID>1001</CorrelationID>
    <Property>
        <Name>password</Name>
        <Value>password</Value>
    </Property>
    <Property>
        <Name>timeout(m)</Name>
        <Value>30</Value>
    </Property>
</Header>
<Reply>
    <Result>OK</Result>
    <Error>
        <code>0.3</code>
    </Error>
</Reply>
</ResponseMessage>"

Code

$xml_post_string = /** @lang text */
                           '<soapenv:Envelope 
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" 
xmlns:soap="http://soap.inf.hexing.cn">
<soapenv:Header/>
<soapenv:Body>
  <soap:doCommand>
     <!--Optional:-->
     <arg0><![CDATA[<?xml version="1.0" encoding="utf-8"?>
<RequestMessage
xmlns="http://iec.ch/TC57/2011/schema/message"
xmlns:m="http://iec.ch/TC57/2011/EndDeviceControls#"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://iec.ch/TC57/2011/schema/message Message.xsd">
<Header>
<Verb>create</Verb>
<Noun>EndDeviceControls</Noun>
<Revision>2.0</Revision>
<Timestamp>2016-01-01T00:00:00+04:30</Timestamp>
<Source>MDM</Source>
<AsyncReplyFlag>true</AsyncReplyFlag>
<ReplyAddress>http://ip:port/AmiWeb/services/Metering</ReplyAddress>
<AckRequired>true</AckRequired>
<User>
<UserID>'.$userName.'</UserID>
</User>
<MessageID>83c643e6-85c5-43c0-9e0a-fa1deb469b72</MessageID>
<CorrelationID>1001</CorrelationID>
<Property>
<Name>password</Name>
<Value>'.$password.'</Value>
</Property>
<Property>
<Name>timeout(m)</Name>
<Value>30</Value>
</Property>
</Header>
<Payload>
<m:EndDeviceControls>
<m:EndDeviceControl>
<m:reason>Disconnect/Reconnect</m:reason>
<m:EndDeviceControlType ref="3.0.211.23"/>
<m:EndDevices>
<m:mRID>'.$msn.'</m:mRID>
<m:Names>
<m:name>Disconnect</m:name>
<m:NameType>
<m:name>ControlType</m:name>
</m:NameType>
</m:Names>
</m:EndDevices>
</m:EndDeviceControl>
</m:EndDeviceControls>
</Payload>
</RequestMessage>
     ]]></arg0>
  </soap:doCommand>
 </soapenv:Body>
</soapenv:Envelope>';
 $headers = array(
                           "Content-type: text/xml;charset=\"utf-8\"",
                           "Accept: text/xml",
                           "Cache-Control: no-cache",
                           "Pragma: no-cache",
                           //"SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice",
                           "Content-length: ".strlen($xml_post_string),
                       ); //SOAPAction: your op URL

                       $url = $soapUrl;

                       // PHP cURL  for https connection

                       $ch = curl_init();
                       curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
                       curl_setopt($ch, CURLOPT_URL, $url);
                       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                       curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
                       curl_setopt($ch, CURLOPT_TIMEOUT, 10);
                       curl_setopt($ch, CURLOPT_POST, true);
                       curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
                       curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

                       // converting
                       $response = curl_exec($ch);
                       curl_close($ch);
                       $xml = simplexml_load_string($response);
                       var_dump($xml);
                       die();

Output

object(SimpleXMLElement)#121 (0) { }

The output is empty. Now I want two things

  1. To convert string to XML
  2. From the returned XML I want to get the value of <AsyncReplyFlag>true</AsyncReplyFlag> from the response

Update 1

As per suggestion, I have added below code

$xml = simplexml_load_string($response);
                        echo $xml->asXML();

Output

<?xml version="1.0" encoding="UTF-8"?>
<ResponseMessage xmlns:ns="http://iec.ch/TC57/2011/schema/message" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://iec.ch/TC57/2011/schema/message Message.xsd">
<Header>
    <Verb>reply</Verb>
    <Noun>EndDeviceControls</Noun>
    <Revision>2.0</Revision>
    <Timestamp>2019-05-04T14:01:48+04:30</Timestamp>
    <Source>HES-BSTC</Source>
    <AsyncReplyFlag>true</AsyncReplyFlag>
    <ReplyAddress>http://ip:port/AmiWeb/services/Metering</ReplyAddress>
    <User>
        <UserID>user</UserID>
    </User>
    <MessageID>F4E15012-D009-4CBC-A610-E937F2620193</MessageID>
    <CorrelationID>1001</CorrelationID>
    <Property>
        <Name>password</Name>
        <Value>password</Value>
    </Property>
    <Property>
        <Name>timeout(m)</Name>
        <Value>30</Value>
    </Property>
</Header>
<Reply>
    <Result>OK</Result>
    <Error>
        <code>0.3</code>
    </Error>
</Reply>
</ResponseMessage>

What I have tried?

$xml = new SimpleXMLElement($response);
print_r($xml);
die();

It gives me an empty result

 $doc = new DOMDocument('1.0', 'utf-8');
                       $doc->loadXML($response);
                       $XMLresults = $doc->getElementsByTagName("AsyncReplyFlag")->item(0)->textContent;
                       echo $XMLresults;
                       die();

It gives me an error

Trying to get property of non-object $XMLresults = $doc->getElementsByTagName("AsyncReplyFlag")->item(0)->textContent;

Still, I am unable to get the value of <AsyncReplyFlag>true</AsyncReplyFlag>

How can I achieve it? Any help would be highly appreciated.

DOMDocument should have no problem extracting it, as a quick one-liner:

echo (@DOMDocument::loadXML($response))->getElementsByTagName("AsyncReplyFlag")->item(0)->textContent;

... or if you want to meticulously check for errors every step of the way,

$xml_errors=[];
set_error_handler(function(int $errno, string $errstr, string $errfile, int $errline, array $errcontext) use(&$xml_errors){
    ob_start();
    call_user_func_array('var_dump',func_get_args());
    $xml_errors[]=ob_get_clean();
});
$domd=new DOMDocument();
$loaded=$domd->loadXML($response);
restore_error_handler();
if(!$loaded){
    if(defined('STDERR')){
        fprintf(STDERR,"%s",$response);
    }
    throw new \RuntimeException("errors parsing XML! xml printed in stderr, parsing errors: ".print_r($xml_errors,true));    
}
$ele=$domd->getElementsByTagName("AsyncReplyFlag");
if($ele->length<1){
    if(defined('STDERR')){
        fprintf(STDERR,"%s",$response);
    }
    throw new \RuntimeException("did not get AsyncReplyFlag in response! (xml printed in stderr)");
}
echo $ele->item(0)->textContent;

SoapClient - Manual, The SoapClient class provides a client for � SOAP 1.1, � SOAP 1.2 servers. public __doRequest ( string $request , string $location , string $action , int $ version from the last request; SoapClient::__getLastResponse — Returns last SOAP response //Translate the XML above in a array, like PHP SOAP function requires soapui unable to parse responses with XML embedded as strings We're using SOAPUI to exercise webmethods and validate integration points between our applications and a Siebel system. This sometimes requires embedding XML requests as strings in some other xml structure, e.g.,

Trying to output a SimpleXMLElement using var_dump() isn't a good idea and as you have seen - doesn't give much.

If you just want to see the XML it has loaded, instead use...

echo $xml->asXML();

which will show you the XML has loaded OK, so then to output the field your after is just

$xml = simplexml_load_string($response);
echo $xml->Header->AsyncReplyFlag;

SOAP - Manual, SoapServer::addFunction — Adds one or more functions to handle SOAP requests; SoapServer::addSoapHeader — Add a SOAP header to the response� Unable to convert soap response string to xml in Yii2; Grails stops at “Configuring classpath” even at a helloworld project; Python win32serviceutil QueryServiceStatus: What does the return value mean? Keydown processes previous character instead of current one; How to convert newick tree format to tree like Hierarchical javascript object

Using the XPath query

$xml = new SimpleXMLElement($xmlData);
echo $xml->xpath('//AsyncReplyFlag')[0];

OR

You can use xml_parser_create

$p = xml_parser_create();
xml_parse_into_struct($p, $xml, $values, $indexes);// $xml containing the XML
xml_parser_free($p);

echo $values[12]['value'];

For other details, you can print_r($values)

PHP simplexml_load_string() Function, Example. 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> Hi All, I have a requirement where in have to convert the JAX-WS SOAP response to a SOAP XML string.Have goggled but couldn't find any way . the client program-me who will invoke the web-service wants to convert the Java Object of response to SOAP XML string.

XmlParser, yii\httpclient\XmlParser | API Documentation, protected array convertXmlToArray ( $xml ). $xml, string|SimpleXMLElement. Xml to process. return, array. XML array representation. can any body tell me how to convert an soap response to xml response. as .net webservices are returning only soap response i want to convert this to xml response ..can any body tell me how to do th

Special Topics: Web Service | The Definitive Guide to Yii 1.1, Web service relies on SOAP as its foundation layer of the communication @ param string the symbol of the stock * @return float the stock price * @soap a lot of XML content which is actually the WSDL for the Web service we defined. The http://hostname/path/to/index.php/stock/quote showed me the xml, but I failed to� to the require section of your composer.json file.. Usage. You need to add [[mongosoft\soapserver\Action]] to web controller. Note, In a service class, a remote invokable method must be a public method with a doc comment block containing the '@soap' tag.

In order to validate XML structure represented in a SOAP::Data object, we need to find a way to convert, or serialize, SOAP::Data objects into XML strings. SOAP::Lite 0.710 manual does not mentioning how to convert SOAP::Data objects into XML strings anywhere.

Comments
  • 1: the string already is XML. 2: $asyncReplyFlag=(@DOMDocument::loadHTML($response))->getElementsByTagName("AsyncReplyFlag")->item(0)->textContent;
  • @hanshenrik not working
  • I am getting this error Call to a member function getElementsByTagName() on boolean
  • For your second option, I am getting this error Use of undefined constant STDERR - assumed 'STDERR'
  • @Faisal weird, there's 2 things here: DOMDocument don't think your xml is valid xml, and your STDERR is not defined, something weird with the way you're executing php but whatever, try #2 again, what do you get this time?
  • @Faisal are you sure? still getting Use of undefined constant STDERR after the if(defined('STDERR')) patch?
  • @Faisal then there is something very wrong with your php installation, where STDERR is defined but you get an error when actually trying to use it... can you try contacting me, i'd like to investigate
  • echo $xml->Header->AsyncReplyFlag; it's giving me empty result
  • Check the XML has some content using echo $xml->asXML();
  • Just to check the next part - try echo $xml->Header->asXML();
  • OK, looks as though it's having problems with the names, can you check this by echo $xml->children()[0]->getName();
  • It gives me error syntax error, unexpected 'echo' (T_ECHO)