PHP json to a JavaScript variable inside an HTML file

I write the following script that creates a nice JSON of all the images under the current folder:

header('Content-type: application/json');

$output = new stdClass();
$pattern="/^.*\.(jpg|jpeg|png|gif)$/i"; //valid image extensions

$dirs = array_filter(glob('*'), 'is_dir');
foreach ($dirs as $dirname) {
  $files = glob(''.$dirname.'/*');
  $images = preg_grep($pattern, $files);
  $output->{$dirname} = $images;

echo json_encode($output, JSON_PRETTY_PRINT);

I have an HTML file with a basic page and I want to display the JSON’s data in a formatted way after some javascript manipulation.

So the question is how can I get the PHP data into a javascript variable?

        <script src="images.php"></script>
        <script type="text/javascript">
            // Desired: Get access to JSON $output


          <img ... >


I tried to put both
and inside that script tag but none of them work so I am guessing I am missing something fundamental here (my ever first experience with PHP 🙂

22 thoughts on “PHP json to a JavaScript variable inside an HTML file”

Leave a Comment