Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
1  
php.net/manual/en/function.json-encode.php could be a place to start –  mplungjan Jul 23 '12 at 12:02
 
It's also not clear as to when and how your JavaScript is to execute. –  Shamim Hafiz Jul 23 '12 at 12:03
 
How were you even allowed to ask this FAQ? –  mplungjan Jul 23 '12 at 12:03
 
@Shamim the Js function is called on HTML button click event –  Emmi Jul 23 '12 at 12:04

marked as duplicate by mplungjan, hakre, PeeHaa, j0k, Graviton Jul 24 '12 at 2:35

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2 Answers

up vote 0 down vote accepted

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

share|improve this answer

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.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.