Search code examples
phpjsonfile-get-contents

File_get_contents with PHP to retrieve JSON output of code as opposed to source code when file is on same server


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?


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();