当前位置: 无忧屋首页 > 文章中心 > PHP >

json参数的传递和接收处理方法

来源:网络

发布人:天道酬勤

发布时间:2024-02-15

php传递JSON参数示例

  1. <?  
  2. function http_post_data($url, $data_string) {  
  3.    
  4.   $ch = curl_init();  
  5.   curl_setopt($ch, CURLOPT_POST, 1);  
  6.   curl_setopt($ch, CURLOPT_URL, $url);  
  7.   curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);  
  8.   curl_setopt($ch, CURLOPT_HTTPHEADER, array(  
  9.    'Content-Type: application/json; charset=utf-8',  
  10.    'Content-Length: ' . strlen($data_string))  
  11.   );  
  12.   ob_start();  
  13.   curl_exec($ch);  
  14.   $return_content = ob_get_contents();  
  15.   //echo $return_content."
  16. ";  
  17.   ob_end_clean();  
  18.    
  19.   $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
  20.   // return array($return_code, $return_content);  
  21.   return $return_content;  
  22. }  
  23.    
  24. $url = "http://127.0.0.1/2.php";  
  25. $data = json_encode(array('a'=>"weqweqwe", 'b'=>2));   
  26.    
  27. //list($return_code, $return_content) = http_post_data($url, $data);  
  28. $aaa = http_post_data($url, $data);  
  29. //print_r($aaa);  
  30. echo $aaa;  
  31.    
  32. $ccc=json_decode($aaa);  
  33. print_r($ccc);  
  34. echo $ccc->b;  
  35.    
  36. echo "<hr>";  
  37. $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';  
  38. var_dump(json_decode($json,true));  
  39.    
  40. ?>
接收json处理示例
  1. <?  
  2. $postData = file_get_contents('php://input');  
  3. echo $postData;  
  4. $data = json_encode(array('a'=>" 234 ", 'b'=>2));  
  5. echo $data;  
  6. ?>

免责声明:文中图文均系网友发布,转载来自网络,如有侵权请联系右侧客服QQ删除,无忧屋网友发布此文仅为传递信息,不代表无忧屋平台认同其观点。