1

I am using file_get_contents to read json data.

My code is :

   //echo $json_url;
    $json_data = file_get_contents($json_url);

I am surprise that, the variable $json_data returns null value. When I echo the variable $json_url, it displays the correct url. Tt also displays json record when I manually enter the url in browser.

What can be error here?

slash197
  • 9,028
  • 6
  • 41
  • 70
npcoder
  • 414
  • 1
  • 5
  • 13

2 Answers2

1

What is the URL?

Note:

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

Furthermore, are url fopen wrappers enabled?

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled.

But you will see why the request failed if you enable error reporting.

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • my url structure is http://localhost/jsread.p?call=favo&user=&lang=en&tree=1266&sort=last&max=500&startpage=1&pagesize=20 I am using codeigniter framework. When I manually my actual url in browser, it displays record. – npcoder Jun 11 '12 at 10:48
  • I still get null values in array. – npcoder Jun 11 '12 at 10:55
  • @shiplu.mokadd.im , its not API. Database is in Progress. So to access it, I am using URL which send me data in JSON format. – npcoder Jun 11 '12 at 11:28
  • @nppCods Then start debugging. What does `var_dump(file_get_contents($json_url));` print? – CodeCaster Jun 11 '12 at 11:28
0

Try to urlencode the url first

$json_data = file_get_contents(urlencode($json_url));
Kasia Gogolek
  • 3,374
  • 4
  • 33
  • 50
  • @shiplu.mokadd.im I never heard of that too, but (as you can see in my answer) it is required when your URL contains "special characters". – CodeCaster Jun 11 '12 at 10:23
  • From PHP Manual: If you're opening a URI with special characters, such as spaces, you need to encode the URI with urlencode(). – Kasia Gogolek Jun 11 '12 at 10:24
  • No it won't work. It will simply convert a valid URL into an invalid one e.g. `http://does-not-require-encoding/file.json` to `http%3A%2F%2Fdoes-not-require-encoding%2Ffile.json`. – Salman A Jun 11 '12 at 10:24