Help, generate javascript with PHP into .*js

Hey

I got this PHP script, wich generates a javascript array,


<?
//PHP SCRIPT: getimages.php
//Header("content-type: application/x-javascript");

//This function gets the file names of all images in the current directory
//and ouputs them as a JavaScript array
function returnimages($dirname="img/gallery/") {

$pattern="(\\.jpg$)|(\\.png$)|(\\.jpeg$)|(\\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'fadeimagesPHP['.$curimage.']=["'.$dirname.$file.'"];'."\
";
$curimage++;
}
}

closedir($handle);
}
return($files);
}
echo 'var fadeimagesPHP=new Array();'."\
"; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names


/* THE Array should look like this
var fadeimagesPHP=new Array()
fadeimagesPHP[0]=["img/gallery/01_2.jpg"]
fadeimagesPHP[1]=["img/gallery/02_2.jpg"]
fadeimagesPHP[2]=["img/gallery/03_2.jpg"]
*/
?> 

It’s not mine, i found it on web:
http://www.javascriptkit.com/javatutors/externalphp2.shtml

What I’m doing now is calling PHP in my main page, with Require once.
But I want it to generate the code directly to the *.js file.

How could this be done? JSON?

If you have time to answer me, please do.

Thank you

Easiest way is to use an external JavaScript file with a .php extension so it gets processed as PHP by the server. Then link it into the web page using the standard <script type=“text/javascript” src=“something.php”> tag

last time i was in similar situation,i devised it and it is working


 if (!function_exists('is_assoc'))
{
	 
	 function is_assoc($array) {
        foreach ( array_keys ( $array ) as $k => $v ) {
            if ($k !== $v)
                return true;
        }
        return false;
    }
}
   
   if (!function_exists('arrayPHPToJS'))
{
	
     function arrayPHPToJS($data) {
        if (is_null($data)) return 'null';
        if (is_string($data)) return "'" . $data . "'";
        if (is_assoc($data)) {
            $a=array();
            foreach ($data as $key => $val )
                $a[]="'" . $key . "' :" .arrayPHPtoJS($val);
            return "{" . implode ( ', ', $a ) . "}";
        }
        if (is_array($data)) {
            $a=array();
            foreach ($data as $val )
                $a[]=arrayPHPtoJS($val);
            return "[" . implode ( ', ', $a ) . "]";
        }
        return $data;
    }
	
}


Seriously just use JSON :slight_smile: json_encode / json_decode