-1

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

asked Jul 23, 2012 at 11:59
4
  • 1
    php.net/manual/en/function.json-encode.php could be a place to start Commented Jul 23, 2012 at 12:02
  • It's also not clear as to when and how your JavaScript is to execute. Commented Jul 23, 2012 at 12:03
  • How were you even allowed to ask this FAQ? Commented Jul 23, 2012 at 12:03
  • @Shamim the Js function is called on HTML button click event Commented Jul 23, 2012 at 12:04

2 Answers 2

0

file_get_contents('file') instead of file('file') is your best bet.

answered Jul 23, 2012 at 12:12
Sign up to request clarification or add additional context in comments.

Comments

0

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.

answered Jul 23, 2012 at 12:04

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.