Search code examples
phpjavascriptarraysdirectoryfile-type

Fill a PHP array with specific filetyoes in a specific directory, to be then read into a JavaScript array


What I'm trying to do is fill a JavaScript array with files which I then want to do something with. The files are all of the type .dae and are in the directories "/collada/basement", "/collada/ground", "/collada/first", and "/collada/roof". I will probably have a separate array for each directory. I realise I will have to use PHP to do this and then transfer them to a JavaScript array somehow. Can someone tell me how please? I've tried to patch it together from other sources but so far no luck.


Solution

  • In the very simplest way:

    <?php
    $files = glob('/collada/basement/*.dae,/collada/ground/*.dae,/collada/first/*.dae,/collada/roof/*.dae);
    ?>
    
    <script type="text/javascript">
    var filelist = <?php echo json_encode($files) ?>;
    </script>
    

    glob() does wildcard file matching pretty much exactly like any standard Unix shell would, and returns an array of what it matched. Then you hop out of PHP mode to output the javascript block, and fill in the file list that glob returned, passing it through json_encode() to turn your PHP array into a Javascript array.