-1

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.

xilex
  • 101
  • 1
  • 8
  • You would have to make the request to *an HTTP server* where the PHP will actually be executed, e.g. `http://localhost/search_list.php`. But since you're then executing PHP, encoding some result as JSON, output the JSON over HTTP, read the HTTP and decode the JSON to a PHP array..... Just skip all that middleware and directly execute the same PHP code as in `search_list.php`; perhaps you just need to put that logic into a function which you can `include` and call. – deceze Jul 18 '16 at 19:27
  • `allow_url_fopen` has to be open on your server - check php settings. Other options offered at http://stackoverflow.com/questions/3488425/php-ini-file-get-contents-external-url – dbmitch Jul 18 '16 at 19:27

1 Answers1

2

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?

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • Thanks for the advice, I will give this a try. I had some autocomplete code that used my PHP script as a data source and it accepted it fine, that's why I was trying to reuse it. I'll be tweaking the data a little bit so I'll following your latter recommendation. – xilex Jul 18 '16 at 19:36