eluong eluong - 4 months ago 13
JSON Question

Can I use file_get_contents() on a dynamically generated JSON output?

I'm trying to implement Tokenize2 on my page.

Part of the code to pull data from a JSON source involves this line:

$obj = json_decode(file_get_contents('search_list.json'), true);


I have a
search_list.php
where I pull data from a mySQL database and generate the JSON content. But if I put
search_list.php
into the
file_get_contents()
it doesn't seem to work. Is there a way to get around this? Thanks.

Answer

file_get_contents() doesn't execute code. It just sucks in some bytes, basically a wrapper around fopen(); fread(); fclose(). That's it.

You'd have to include your script, e.g.

ob_start();
include('yourscript.php');
$json = ob_end_clean();

but at that point, you should ask yourself while you're going to all the trouble of including/executing that script, forcing it to generate a JSON string, and tearing that json string apart into a PHP array again. Total and absolute waste of cpu resources.

You should do something better, like:

function whatever($output = 'json') {
       ... build data structure
       if ($output == 'json') {
         echo json_encode($data);
       } else 
         return $data;
       }
    }

It's already PHP code, you already had all your data in a PHP data structure, so why do the wasteful step of data->json->data?

Comments