0

I'm trying to return JSON results from a page but I get the following error using file_get_contents(): " failed to open stream: HTTP request failed! "

Can someone tell me why I get this error?

<?

$newURL = 'https://api.qwant.com/api/search/images?count=10&offset=1&q=Spicy 
Cranberry Cavolo Nero (Kale)';



$returnedData = file_get_contents($newURL);

?>
  • Any reason not to have "https://api.qwant.com/api/search/images?count=10&offset=1&q=Spicy%20Cranberry%20Cavolo%20Nero%20(Kale)" instead of what you have right now? With %20 for each space – RAZERZ Jan 05 '18 at 22:07
  • Possible duplicate of [PHP file\_get\_contents() returns "failed to open stream: HTTP request failed!"](https://stackoverflow.com/questions/697472/php-file-get-contents-returns-failed-to-open-stream-http-request-failed) – Liora Haydont Jan 05 '18 at 22:09
  • have your tried to escape the parameters correctly? for example, replace the spaces with `%20` in the url. – Ibu Jan 05 '18 at 22:24
  • @RAZERZ I tried doing a urlencode on the query itself but it gives me a different error (Too many request): $baseURL = 'https://api.qwant.com/api/search/images?'; $query = urlencode("count=10&offset=1&q=Spicy Cranberry Cavolo Nero (Kale)"); $composedURL = $baseURL.$query; $returnedData = file_get_contents($composedURL); – user1493588 Jan 05 '18 at 22:39

1 Answers1

1
  1. Never use <? ?>. Use only <?php ?> or <?= ?>
  2. urlencode() use only on values of your parameters, not on the whole parameter's line.
  3. file_get_contents() is not a really good method to receive data from the outer servers. Better use CURL.

    <?php
    
    // Your URL with encoded parts
    $newURL = 'https://api.qwant.com/api/search/images?count=10&offset=1&q='.urlencode('Spicy Cranberry Cavolo Nero (Kale)');
    
    // This is related to the specifics of this api server, 
    // it requires you to provide useragent header
    $options = array(
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_USERAGENT => 'any-user-agent-you-want',
    );
    
    // Preparing CURL
    $curl_handle = curl_init($newURL);
    
    // Setting array of options
    curl_setopt_array( $curl_handle, $options );
    
    // Getting the content
    $content = curl_exec($curl_handle);
    
    // Closing conenction
    curl_close($curl_handle);
    
    // From this point you have $content with your JSON data received from API server
    
    ?>