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 🙂

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 ?>";

    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


Leave a Comment