user1493588
user1493588

Reputation: 3

PHP file_get_contents() throws error "failed to open stream: HTTP request failed! <!doctype html>"

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);

?>

Upvotes: 0

Views: 2411

Answers (1)

Ivan Ponomarev
Ivan Ponomarev

Reputation: 46

  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
    
    ?>
    

Upvotes: 1

Related Questions