user3900720
user3900720

Reputation: 131

How to read multiple line from file and split it to array in php

I hava a file that contains :

ali 123456
vali 154667

I want to read this file and split into array like this:

$array[0][0]=ali 
$array[0][1]=123456
$array[1][0]=vali
$array[1][1]=154667 

I searched about this and saw w3schools documents, But I can't read my wanted! Please show me How should I do it!

Best Regard, Minallah Tofig

Upvotes: 1

Views: 7232

Answers (3)

user3781087
user3781087

Reputation: 419

Firstly, initialize the array:

$myArray = array();

open the file:

$file = fopen("myfile.txt", "r");

iterate the file line by line

while (!feof($file)) {
   $line = fgets($file);
   $myArray[] = explode(' ', $line);
}

close the file

fclose($file);

$myArray contains your result

Upvotes: 1

Charlotte Dunois
Charlotte Dunois

Reputation: 4680

You can use the php function file() to read the file line by line into an array. Then you have to loop through it and explode() by the white space.

$array = file('file.txt.');
foreach($array as $key => $line) {
    $array[$key] = explode(" ", $line);
}

http://ch2.php.net/manual/en/function.file.php

http://ch2.php.net/manual/en/function.explode.php

Upvotes: 3

christopher
christopher

Reputation: 27346

Firstly, this question explains how you read a file line by line in PHP. The top and bottom of it is:

$handle = fopen("inputfile.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        // process the line read.
    }
} else {
    // error opening the file.
}  
fclose($handle);

Now in your case, you've got a structured line. Namely.

<name><space><value>

I would strongly, strongly argue against using a multi dimensional array for this. Instead, go for an OOP based solution. First, define a class.

class Person {
    protected $name;
    protected $code;

    function __construct($line) {
        // Split and load.
    }
}

Then you can create an array of Person objects.

$people = array();

Then cycle through each line and create a Person object.

while(($line = fgets($handle)) !== false) {
    $people[] = new Person($line);
}

Now you've got all the pieces of the puzzle, it's up to you to put them all together!

Upvotes: 0

Related Questions