php - Use file_get_contents() and implode() to pass array to javascript not working -
i developing simple image gallery shows images , related caption. images inside directory , caption in (as single files). php script lists files in both directories , pass arrays javascript wich change image , caption when user press 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 js $captions = '["' . implode('", "', $filesc). '"]'; $images = '["' . implode('", "', $filesi). '"]'; ?> <script> var captions = <?php echo $captions; ?>; var images = <?php echo $images; ?>; [...]
images work , can print caption's file name instead of caption i.e.
$filesc[$x] = $filename;
but when use "file_get_contents()" read file gallery stops working.
if echo $captions , manually set $captions same output e.g.
$captions='["first caption","second caption", "..."]';
the gallery works properly, array should formatted...
thank in advance
solution creating array 2 empty elements (0,1) in order avoid ./ , ../ in file list, have added +2 lsi index.
for($x = 0; $x < $lenght-2; $x++) { $filesi[$x] = $imgdirectory."/".$lsi[$x+2]; }
in addition have used json_encode, suggested, instead of manual json encodig. output seems same gallery works!
var images = <?php echo json_encode($filesi); ?>;
in js have escape new lines in strings this:
var multilinestring = "this is\ example";
maybe try use trim() , str_replace() if don't want make easier json_encode().
update
then wrong. did know can push items arrays $array[] = 'item';
?
Comments
Post a Comment