Mick
Mick

Reputation: 3

Getting data from txt file to php's array

I have some data in txt file that looks like:

data1
data2
....

I want it to export it into an array so I'm trying to make it with PHP:

<?php
$file = fopen("myfile.txt", "r");
$members = array();

while (!feof($file)) {
   $members[] = fgets($file);
}

fclose($file);

var_dump($members);
?>

However it generates associative array like [0]=> string(5) "data1" [1]=> string(5) "data2" and I need it to work in javascript, so how can I easily export it to look like ["data1","data2",...]?

Upvotes: 0

Views: 44

Answers (1)

Eugen Rieck
Eugen Rieck

Reputation: 65334

You use the word array in a double sense: What you see from print_r() is an array in PHP representation, what you want to get is an array in JSON representation. Both of them descrive essentially the same data structure.

The way to convert this, is to use json_encode():

echo json_encode($members);

will do the trick.

Upvotes: 1

Related Questions