views:

32

answers:

1

Hi All, I want to decode Json returned from the WebService, And it should set a cookie, that i want to use to call next WebService API. I am not sure how to set a cookie, and decode this json.

I tried decoding it, but get the error. I need to extract sessionId. You can use the WebService.. I have put this on Internet.

Here is my code sample

 <?php //extract data from the post
       extract($_POST); //set POST variables
       $url = 'http://202.83.243.119/ems/loginByEID.json';
       $fields = array(
                   'eid'=>urlencode("7ea888b6-36e9-49db-84f3-856043841bef")
               );
      //url-ify the data for the POST
       foreach($fields as $key=>$value) {
       $fields_string .=
       $key.'='.$value.'&'; }
       rtrim($fields_string,'&');

       //open connection $ch = curl_init();

       //set the url, number of POST vars,
       POST data
       curl_setopt($ch,CURLOPT_URL,$url);
       curl_setopt($ch,CURLOPT_POST,count($fields));
       curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);

       //execute post $result =
       curl_exec($ch);

       //close connection curl_close($ch);  
       //decoding Json $obj =
       json_decode($result);

       print $obj->{'stat'};  

       ?>
+4  A: 
  1. Use setcookie() to set a cookie.
  2. Avoid extract() like the plague; it can be used to introduce any client-specified variables into your code.
  3. Use $fields_string = http_build_query($_GET) to build a query string instead of your hodge-podge above.
  4. Format your code properly. For example, you put the $obj = inside the previous comment line.
janmoesen
Regarding (3), the CURLOPT_POSTFIELDS option also accepts an associative array, so he doesn't even have to build a query string at all.
Daniel Egeberg
Thanks Janmoesen/Daniel. I guess setcookie() will not work, as it is web server to web server communication and Curl functions work very well.Answer Here : http://www.daniweb.com/forums/thread78356.html
Ajay
Still looking for a good way to be able to parse json. var_dump will work? Regards, Ajay
Ajay
Ajay: now I understand your cookie question. When using cURL, you can specify a cookie file or jar, or set the cookie HTTP header directly. See http://php.net/curl_setopt
janmoesen
Ajay: as for parsing JSON, you already have `json_decode`, which gives you a traversable object. (You can do stuff like `$obj->stat->foo->bar`.) Is that not enough?
janmoesen