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:

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

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

        ...

        <div>
          <img ... >
        </div>

    </body>
</html>

I tried to put both https://stackoverflow.com/a/61212271/1692261
and https://stackoverflow.com/a/50801851/1692261 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 🙂

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

  1. you should focus on what needs to be done, but currently you are trying to implement your own idea. maybe you should change your approach and do what you want in another way?
    passing php variable to js is possible. but for what reason do you need this json? if you want to operate with it to generate html (f.e show images to user) you can do it on pure php without js. if you need exactly json you can generate json file with php and and get this file via additional js request. but the simplest way is

    // below php code that generates json with images
    $images = json_encode($output, JSON_PRETTY_PRINT);
    ...
    // php code but in html template
    <script type="text/javascript">
       var images = "<?= $images ?>";
    </script>
    

    I won’t guarantee that this js line is going to work but you get the idea)

    P.S you dont need to use stdClass for such purposes. we do it via arrays (in you case it will be associative arrays), arrays are very powerful in php. json_encode() will generate same json from both array or object. but if this part of code works fine that let it stay as it is

    Reply

Leave a Comment