2010-06-25 124 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