Hassan Ajk
Hassan Ajk

Reputation: 135

php: file_get_contents(url) failed to open stream when calling a page that has a json response

I have the following code:

<?php
//first try
$url = 'http://www.omdbapi.com';
echo '<pre>';
print_r(file_get_contents($url));
echo '</pre>';


//second try
$url = 'http://www.omdbapi.com/?t=the dark night';
echo '<pre>';
print_r(file_get_contents($url));
echo '</pre>';
?>

The first try works fine. However, the second try give the following error message with no more details: $file_get_contents(http://www.omdbapi.com/?t=the dark night): failed to open stream: HTTP request failed!

Note that,pc has windows 8.1 x64, I've tried both wamp server and xampp. I did make sure that both of $php.ini files have enabled both of the extentions $extension=php_openssl.dll and $extension=php_curl.dll

Upvotes: 1

Views: 331

Answers (2)

emiliopedrollo
emiliopedrollo

Reputation: 950

Try to encode your url using urlencode:

$url = 'http://www.omdbapi.com/?t='.urlencode('the dark night');
echo '<pre>';
print_r(file_get_contents($url));
echo '</pre>';

Upvotes: 1

Federkun
Federkun

Reputation: 36944

The documentation of file_get_contents say

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

So replace

$url = 'http://www.omdbapi.com/?t=the dark night';

with

$url = 'http://www.omdbapi.com/?t='.urlencode('the dark night');

Upvotes: 3

Related Questions