简体   繁体   中英

Use file_get_contents() and implode() to pass array to javascript not working

I am developing a simple image gallery which shows images and related caption. All images are inside a directory and caption in another (as single files). A php script lists all files in both directories and pass arrays to a javascript wich change image and caption when the user press a button.

            [...]    
            for($x = 2; $x < $lenght; $x++) {
                $filesi[$x] = $imgdirectory."/".$lsi[$x];
            }

            for($x = 2; $x < $lenght; $x++) {
                $filename = $capdirectory."/".$lsc[$x];
                $filesc[$x] = file_get_contents($filename);
            }

            //Create array for JS
            $captions =  '["' . implode('", "', $filesc). '"]';
            $images =  '["' . implode('", "', $filesi). '"]';
?>    
<script>
            var captions = <?php echo $captions; ?>;
            var images = <?php echo $images; ?>;
            [...]

Images work properly and I can also print caption's file name instead of caption ie

$filesc[$x] = $filename;

but when I use "file_get_contents()" to read file the gallery stops working.

If I echo $captions and manually set $captions with the very same output eg

$captions='["first caption","second caption", "..."]';

the gallery works properly, so the array should be properly formatted...

Thank you in advance

SOLUTION I was creating an array with two empty elements (0,1) in order to avoid ./ and ../ in file list, so I have added a +2 to the lsi index.

for($x = 0; $x < $lenght-2; $x++) {
                $filesi[$x] = $imgdirectory."/".$lsi[$x+2];
            }

In addition I have used json_encode, as suggested, instead of manual json encodig. The output seems to be the same but now the gallery works!

var images = <?php echo json_encode($filesi); ?>;

In JS you have to escape new lines in strings like this:

var multilineString = "this is\
just an example";

Maybe try to use trim() and str_replace() if you don't want to make it easier with json_encode().

UPDATE

Then I was wrong. Did you know that you can push items to arrays with just $array[] = 'item'; ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM