1

So I know file() returns every new line into an array.

$plugins = file("plugins.txt");
foreach($plugins as $plugin) {
    echo $plugin;
 }

Which returns

item1 item2 item3

In one line. Though, I know PHP thinks it's an array, JS doesnt, if I convert the above PHP script into a function and then do:

var pluginsList = <?php echo filetoArray(); ?>;

Which returns in console

var pluginsList = item1 item2 item3

While I was hoping for:

var pluginsList = [item1,item2,item3];

How would I make sure it reutns an array so JS can read?

EDIT: So thanks to the answers, I got an array finally. But it returns like this:

["item1\r\n","item2\r\n","item3\r\n","item4"]

Though, I want the \r\n to be removed. What I have so far: the str_replace doesn't do anything, it's the same.

    $plugins = file("plugins.txt");
    $plugins = json_encode($plugins);
    $plugins = str_replace("\n\r", "", $plugins);
    echo $plugins;
3
  • I believe something you are looking for is called JSON which gives the PHP the ability to pass PHP Code into JS, and JS into PHP Commented Dec 2, 2012 at 16:38
  • Sorry... tried to be descriptive as possible :/ Commented Dec 2, 2012 at 16:38
  • make array and use json_encode() Commented Dec 2, 2012 at 16:38

1 Answer 1

4

Easy as this:

$plugins = file("plugins.txt");
$plugins = str_replace(array("\r\n", "\r", "\n"), '', $plugins);
$output = json_encode($plugins);
print $output;
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Though now it's returning \n\r after every line, and rtrim() isn't removing is for some reason...............
@devs look at nl2br(); if you want to convert the \n\r to a new line. else if you want it removed all together, use str_replace("\n\r", "", $VarToReplacein);
@ArmelLarcier your edit won't replace either, since json_encode will already convert the CR/LFs to escaped strings itself. Better to perform a str_replace before the encode: codepad.org/czjr2CHN

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.