Search code examples
phpweb-servicessimplexmlsoap-client

Error when parsing the webservice response in PHP


I am at the learning stage of PHP. I have tried to invoke a sample webservice from a single PHP script. I started with StockQuote service. Below is the script I have written.

<?php
   echo "Stock Quote service check";
   require_once 'nusoap.php';
   $wsdl="http://www.webservicex.net/stockquote.asmx?wsdl";
   $client=new SoapClient($wsdl);

   $param=array('symbol'=>'GOOG');  
   $response = $client->__soapCall('GetQuote', array($params));
   $quotes = simplexml_load_string($response->GetQuoteResult);

   echo $quotes;
   //->Stock[0];

   ?>

Below is the warning i got:

Deprecated: Assigning the return value of new by reference is deprecated in C:\wamp\www\nusoap.php on line 7384

Warning: Creating default object from empty value in C:\wamp\www\nusoap.php on line 75

Notice: Undefined variable: params in C:\wamp\www\URLExample.php on line 8

Warning: simplexml_load_string(): Entity: line 1: parser error : Start tag expected, '<' not found in C:\wamp\www\URLExample.php on line 9

Warning: simplexml_load_string(): exception in C:\wamp\www\URLExample.php on line 9

Warning: simplexml_load_string(): ^ in C:\wamp\www\URLExample.php on line 9

Notice: Trying to get property of non-object in C:\wamp\www\URLExample.php on line 11

When I am invoking the function manually I got the below output. enter image description here

Please help to parse the response XML to get the < Stock> value. I found similar type of questions (Question No: #22060990) but nothing helps to my situation.


Solution

  • You have an error in your code, "$param" should be "$params",

    Also, echo $quotes wont work because $quotes is a SimpleXML object, so you need to access it as an object($quotes->Stock->Last for example)

    <?php
    echo "Stock Quote service check";
    require_once 'nusoap.php';
    $wsdl="http://www.webservicex.net/stockquote.asmx?wsdl";
    $client=new SoapClient($wsdl);
    $params=array('symbol'=>'GOOG');  
    $response = $client->__soapCall('GetQuote', array($params));
    $quotes = simplexml_load_string($response->GetQuoteResult);
    echo $quotes->Stock->Last;
    ?>
    

    You can get following data from $quotes->Stock object:

    ["Symbol"]=>
    string(4) "GOOG"
    ["Last"]=>
    string(6) "528.48"
    ["Date"]=>
    string(8) "2/2/2015"
    ["Time"]=>
    string(6) "4:00pm"
    ["Change"]=>
    string(5) "-6.04"
    ["Open"]=>
    string(6) "531.44"
    ["High"]=>
    string(6) "533.00"
    ["Low"]=>
    string(6) "518.55"
    ["Volume"]=>
    string(7) "2842249"
    ["MktCap"]=>
    string(6) "359.5B"
    ["PreviousClose"]=>
    string(6) "534.52"
    ["PercentageChange"]=>
    string(6) "-1.13%"
    ["AnnRange"]=>
    string(15) "487.56 - 604.83"
    ["Earns"]=>
    string(6) "21.021"
    ["P-E"]=>
    string(5) "25.43"
    ["Name"]=>
    string(11) "Google Inc."