简体   繁体   中英

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",...] ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM