2010-06-25 122 views
0

我想解码从WebService返回的Json,并且它应该设置一个cookie,我想用它来调用下一个WebService API。我不知道如何设置一个cookie,并解码这个JSON。PHP中的json_decode设置cookie

我试着解码它,但得到错误。我需要解压sessionId。你可以使用WebService ..我已经把它放在了Internet上。

这里是我的代码示例

<?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
  1. 使用setcookie()设置cookie。
  2. 避免extract()喜欢瘟疫;它可以用来将任何客户端指定的变量引入您的代码中。
  3. 使用$fields_string = http_build_query($_GET)建立一个查询字符串,而不是上面的hodge-podge。
  4. 正确设置您的代码。例如,您将$obj =放入之前的注释行中。
+1

关于(3),CURLOPT_POSTFIELDS选项也接受一个关联数组,所以他甚至不必构建查询字符串。 – 2010-06-25 06:54:06

+1

谢谢Janmoesen/Daniel。我猜setcookie()将不起作用,因为它是Web服务器到Web服务器的通信和Curl函数工作得很好。 在这里回答:http://www.daniweb.com/forums/thread78356.html – Ajay 2010-06-25 08:21:57

+0

仍在寻找一种能够解析json的好方法。 var_dump会起作用吗?问候,Ajay – Ajay 2010-06-25 08:25:00