eluong eluong - 1 year ago 81
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
where I pull data from a mySQL database and generate the JSON content. But if I put
into the
it doesn't seem to work. Is there a way to get around this? Thanks.

Answer Source

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.

$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?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download