记一次file_get_contents报failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request的错

不能用此函数获取网页内容,会报failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request的错,但是手动执行该URL的时候就可以。

网上查了很多解决办法,都不可以不行。

包括修改user_agent=”Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)” ,

改换curl

1  public function geturldata($url) { 
2         $ch = curl_init(); 
3         curl_setopt ($ch, CURLOPT_URL, $url); 
4         curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
5         curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10); 
6         $content = curl_exec($ch);
7         return $content;
8 } 

或者是增加参数使函数不报错等方法。

1 $context = stream_context_create(array(
2   'http' => array(
3      'ignore_errors'=>true,
4      'method'=>'GET'
5      // for more options check http://www.php.net/manual/en/context.http.php
6    )
7 ));
8 $response = json_decode(file_get_contents($url, false, $context));

最后经过观察参数发现,我的URL其中一个参数中间是有空格的。

导致URL断掉了,所以不能执行。

所以我把可能会有空格的参数都加上了urlencode就可以了。

猜你喜欢

转载自www.cnblogs.com/lotus-white/p/9110513.html