File_get_contents with PHP to retrieve JSON output of code as opposed to source code when file is on same server
Get the solution ↓↓↓I have a server file with a .php extension that retrieves data from a database and outputs it as JSON. I am trying to get this output from a separate file in the same directory, however, when I use file_get_contents, instead of retrieving the output, it is retrieving the source code. When applied to an external URL, file_get_contents obviously can't get the source of the files on the server but only the output (albeit the source code of the output).
The file outputs its content with:
header("Content-Type: application/json");
echo json_encode(array('item'=>$dataobject));
I am trying to get the output with:
$object = file_get_contents("myfile.php");
What is the property way to retrieve the output of a file, as opposed to source code when the file is in the same directory?
Answer
Solution:
The direct route would be to use a URL instead of a file path so that the data is fetched over HTTP and the web server generates the response to the URL by executing the PHP program.
The better approach would be to refactor the code into a function, include the file, then call the function.
mylib.php
function getJSON() {
return json_encode(array('item'=>$dataobject));
}
myfile.php
include("mylib.php");
header("Content-Type: application/json");
echo getJSON();
other.php
include("mylib.php");
$object = getJSON();
Answer
Solution:
I don't understand, why you want do that. That is not a good approach. But anyway, this might be helpful.
File 1 - test1.php
<?php
echo json_encode(['year'=>2020]);
?>
File 2 - test2.php
<?php
echo file_get_contents("http://localhost/test1.php");
?>
Remove localhost with your url.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: sqlstate[hy000] [1698] access denied for user 'root'@'localhost'
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.