Reputation: 359
I am trying to set up a php script that returns some db entries to a json file. The script seems to be working when I read it from another website, however, when I try to read the output from the same folder (for testing purposes) it does not work. php code for generating the json:
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 01 Jan 1996 00:00:00 GMT');
header('Content-type: application/json');
//snipped sql magic
echo json_encode($rows);
When I visit the page on my site it will return what is expected:
[{"id":96,"name":"name1"},{"id":39,"name":"name2"}]
So far so good. However, when I try to read the output of this file in another php file in the same folder, like
$json = file_get_contents(urlencode('json.php')); //same result without the urlencode
echo var_dump($jsonData);
It will return the php code and not the content of the json file. I don't understand why this is. Any thoughts?
Upvotes: 0
Views: 416
Reputation: 1971
It's totally normal. The method 'file_get_contents' read the content of a file, and it will not execute the php scripts it contains.
You may use 'include' or 'curl' to do that.
'include' will read a file and insert the php script it contains into the current script. 'curl' will call a URL, so it will actually ask your server for the php file.
As you are using 'header' inside your script, it would say 'curl' is what you need but maybe 'include' is enough.
Here is a CURL example:
$ch = curl_init("http://localhost/your/script.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$json = json_decode(curl_exec($ch));
curl_close($ch);
More info:
Upvotes: 2
Reputation: 1206
You just return json_encode
ed data in your test file.
// json_data.php
return json_encode(array(
'id' => 5,
'name' => 'John'
));
And retrieve those data with include
header('Content-Type: application/json');
$json = include 'json_data.php';
echo urlencode($json);
Or you even can return already urlencode
ed data in json_data.php
script.
return urlencode(json_encode(array(
'id' => 5,
'name' => 'John'
)));
Hope, this will help you.
Upvotes: 0