Reputation: 541
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;
Upvotes: 1
Views: 507
Reputation: 16027
Easy as this:
$plugins = file("plugins.txt");
$plugins = str_replace(array("\r\n", "\r", "\n"), '', $plugins);
$output = json_encode($plugins);
print $output;
Upvotes: 4