PHP file_get_contents() returns “failed to open stream: HTTP request failed!”

前端 未结 11 763
名媛妹妹
名媛妹妹 2020-11-22 13:03

I am having problems calling a url from PHP code. I need to call a service using a query string from my PHP code. If I type the url into a browser, it works ok, but if I use

相关标签:
11条回答
  • 2020-11-22 13:35

    Could this be your problem?

    Note: If you're opening a URI with special characters, such as spaces, you need to encode the URI with urlencode().

    0 讨论(0)
  • 2020-11-22 13:37

    I notice that your URL has spaces in it. I think that usually is a bad thing. Try encoding the URL with

    $my_url = urlencode("my url");
    

    and then calling

    file_get_contents($my_url);
    

    and see if you have better luck.

    0 讨论(0)
  • 2020-11-22 13:37

    I got a similar problem , I parsed the youtube url. The code is;

    $json_is = "http://gdata.youtube.com/feeds/api/videos?q=".$this->video_url."&max-results=1&alt=json";
    $video_info = json_decode ( file_get_contents ( $json_is ), true );     
    $video_title = is_array ( $video_info ) ? $video_info ['feed'] ['entry'] [0] ['title'] ['$t'] : '';
    

    Then I realise that $this->video_url include the whitespace. I solved that using trim($this->video_url).

    Maybe it will help you . Good Luck

    0 讨论(0)
  • 2020-11-22 13:43

    You basically are required to send some information with the request.

    Try this,

    $opts = array('http'=>array('header' => "User-Agent:MyAgent/1.0\r\n")); 
    //Basically adding headers to the request
    $context = stream_context_create($opts);
    $html = file_get_contents($url,false,$context);
    $html = htmlspecialchars($html);
    

    This worked out for me

    0 讨论(0)
  • 2020-11-22 13:46

    file_get_contents() utilizes the fopen() wrappers, therefore it is restricted from accessing URLs through the allow_url_fopen option within php.ini.

    You will either need to alter your php.ini to turn this option on or use an alternative method, namely cURL - by far the most popular and, to be honest, standard way to accomplish what you are trying to do.

    0 讨论(0)
  • 2020-11-22 13:50

    Use this

    file_get_contents($my_url,null,null);
    
    0 讨论(0)
提交回复
热议问题