昨天的一個(gè)任務(wù),用POST 方式向一個(gè)指定的URL推送數(shù)據(jù)。以前都用的數(shù)組來完成這個(gè)工作。
現(xiàn)在要求用json格式。感覺應(yīng)該是一樣的。開寫。
1 <?php 2 $post_url = "http://news.php"; 3 $post_data = json_encode($output_news);//$output_news處理好的數(shù)組 4 $ch = curl_init();//初始化 5 curl_setopt($ch, CURLOPT_TIMEOUT, '30');//超時(shí)時(shí)間 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)){//出錯(cuò)則顯示錯(cuò)誤信息13 PRint curl_error($ch);14 }15 curl_close($ch);
承接頁用$_POST接收,打印了一下發(fā)現(xiàn)是空的。上網(wǎng)搜索了一下發(fā)現(xiàn)PHP默認(rèn)只識別application/x-www.form-urlencoded標(biāo)準(zhǔn)的數(shù)據(jù)類型。
修改頭信息也沒有結(jié)果。。。
只能通過以下方式獲得數(shù)據(jù)<?php//第一種方法$news = $GLOBALS['HTTP_RAW_POST_DATA'];//第二種方法$news = file_get_contents("php://input");
最后修改了修改了數(shù)據(jù)才能接收到。修改結(jié)果
<?phpcurl_setopt($ch,CURLOPT_POSTFIELDS,"news=".$post_data);?>這樣承接頁就用$_POST就可以接收到數(shù)據(jù)。
新聞熱點(diǎn)
疑難解答
圖片精選