Home >Backend Development >PHP Tutorial >How to split text into array using spaces in PHP
PHP reads a text file line by line, then processes the space-delimited text and outputs it as an array.
Text document text.txt content:
1 Field 1 Field 2
2 Field 1 Field 2
3 Field 1 Field 2
4 Field 1 Field 2
Separate the text with spaces and use PHP to pass it through Process, the output is an array, the following is the code
$file = fopen("text.txt", "r") or exit("Unable to open file!");
while(!feof($ file))
{
$arr = split(' ', fgets($file));
print_r($arr);
}
fclose($file);
?>
Output result:
Array (
[0] => 1
[1] => Field 1
[2] => Field 2
)
Array (
[0] => 2
[1] => Field 1
[2] => Field 2
)
Array (
[0] => 3
[1] => Field 1
[2] => Field 2
)
Array (
[0 ] => 4
[1] => Field 1
[2] => Field 2
)
In this way, PHP uses spaces to divide text into arrays.
This php tutorial is provided by JS Code Station Produced by