0

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?

2 Answers 2

2

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:

Sign up to request clarification or add additional context in comments.

1 Comment

ok, thanks. I understand better now. I learned something today, so the day was not wasted :) include did the trick.
0

You just return json_encodeed 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 urlencodeed data in json_data.php script.

return urlencode(json_encode(array(
    'id' => 5,
    'name' => 'John'
)));

Hope, this will help you.

2 Comments

This will not work anymore for distant call like XHR.
Agree with this, but this solution is simple and works exactly for read the output from the same folder (for testing purposes).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.