1

i am having difficulties with extracting specific text from a text file. I have tried many different ways like using fopen or file to open the file but this wont allow me to use any of the string functions. So i have decided to use file_get_contents and extract the text i want with the string methods as follows:

    <?php  

        $data = [];  
        $file =   
        file_get_contents("data.txt", 0, NULL, 148);  
             list($id, $data_names) = preg_split('[:]', $file);  
             array_push($names, $data_names);  
             echo $emails[0];  

    ?>  

I used preg_split to split the text i want at a specific character (:) and i put the data in an array. Which worked for the first line but i don't know how to go about doing it for the rest of the lines, i've tried a while loop but that just ends up in an infinite loop.

data.txt formatted like this:

1:hannah.Smith
2:Bob.jones
3:harry.white
....

Any suggestions on how to do this or a better approach would be greatly appreciated.

  • https://stackoverflow.com/q/5299471/1531971, https://stackoverflow.com/q/25261902/1531971, https://www.ibm.com/developerworks/library/os-php-readfiles/index.html –  Jul 05 '18 at 16:00

2 Answers2

0

There is a function for that. This isn't CSV but change the delimiter. To just get the names:

$handle = fopen("data.txt", "r"));
while(($line = fgetcsv($handle, 0, ":")) !== FALSE) {
    $names[] = $line[1];
}

To index the names by the ids:

while(($line = fgetcsv($handle, 0, ":")) !== FALSE) {
    $names[$line[0]] = $line[1];
}

To get the ids and names in a multidimensional array, use:

while(($names[] = fgetcsv($handle, 0, ":")) !== FALSE) {}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
0

Well you are not assigning the return value of file_get_contents to a variable. So the contents of the file are not being used.

You can use the file function. It reads the contents of a file to an array. Each element of the array is a line in the file. You can then loop over the array and parse each line. For example:

$names = array();
$file  = file_get_contents("data.txt");

for ($count = 0; $count < count($file); $count++) {
    list($id, $name) = $file[$count];
    $names[]         = $name;
}

/** print the contents of the names array */
print_R($names);
Nadir Latif
  • 3,690
  • 1
  • 15
  • 24