昨天的一個任務,用POST 方式向一個指定的URL推送數據。以前都用的數組來完成這個工作。
現在要求用json格式。感覺應該是一樣的。開寫。
1 <?php 2 $post_url = "http://news.php"; 3 $post_data = json_encode($output_news);//$output_news處理好的數組 4 $ch = curl_init();//初始化 5 curl_setopt($ch, CURLOPT_TIMEOUT, '30');//超時時間 6 curl_setopt($ch, CURLOPT_HTTPHEADER, array('Keep-Alive: 300','Connection: keep-alive')) ; 7 curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; GTB7.4; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2)'); 8 curl_setopt($ch, CURLOPT_POST,1); 9 curl_setopt($ch, CURLOPT_URL,$post_url);10 curl_setopt($ch, CURLOPT_POSTFIELDS,$post_data);11 $contents = curl_exec($ch);12 if(curl_errno($ch)){//出錯則顯示錯誤信息13 PRint curl_error($ch);14 }15 curl_close($ch);
承接頁用$_POST接收,打印了一下發現是空的。上網搜索了一下發現PHP默認只識別application/x-www.form-urlencoded標準的數據類型。
修改頭信息也沒有結果。。。
只能通過以下方式獲得數據<?php//第一種方法$news = $GLOBALS['HTTP_RAW_POST_DATA'];//第二種方法$news = file_get_contents("php://input");
最后修改了修改了數據才能接收到。修改結果
<?phpcurl_setopt($ch,CURLOPT_POSTFIELDS,"news=".$post_data);?>這樣承接頁就用$_POST就可以接收到數據。
新聞熱點
疑難解答