Possible Duplicate:
Inserting PHP array into Javascript array
I'm reading a file in server with php and storing the file content in a variable. now i want to access the variable with javascript, Since I need to split the contents with tab delimited and add the content as options to a Select tag.
<?php
//read the 'file' content to lines variable
$lines = file('file');
?>
Javascript to access the PHP variable($lines):
<script type="text/javascript" >
function readData(){
var s = '<? echo $lines ?>';
alert(s);
}
</script>
Where alert pops up only with Array text
What Should I do so that the data stored in $lines array will be accessed in javascript array variable
-
1php.net/manual/en/function.json-encode.php could be a place to startmplungjan– mplungjan2012年07月23日 12:02:09 +00:00Commented Jul 23, 2012 at 12:02
-
It's also not clear as to when and how your JavaScript is to execute.Shamim Hafiz - MSFT– Shamim Hafiz - MSFT2012年07月23日 12:03:06 +00:00Commented Jul 23, 2012 at 12:03
-
How were you even allowed to ask this FAQ?mplungjan– mplungjan2012年07月23日 12:03:45 +00:00Commented Jul 23, 2012 at 12:03
-
@Shamim the Js function is called on HTML button click eventEmmi– Emmi2012年07月23日 12:04:32 +00:00Commented Jul 23, 2012 at 12:04
2 Answers 2
file_get_contents('file') instead of file('file') is your best bet.
Comments
file function is to use get file contents in an array and then iterate (say in foreach) line by line.like:
foreach ($lines as $line_num => $line) {
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}
You can use file_get_contents() to return the contents of a file as a string. like
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
if you are using contents in JS, you 'll have to take care of special characters like quotes.