0

I have a text file which consists of content that is comma separated.

Let my file be test.txt. The content is:

text1, text2, text3

I want to read this file and assign these three values into 3 variables.

I have checked readfile(filename,include_path,context)

dingo_d
  • 11,160
  • 11
  • 73
  • 132
Santhucool
  • 1,656
  • 2
  • 36
  • 92

2 Answers2

6

Try this

$textCnt  = "text.txt";
$contents = file_get_contents($textCnt);
$arrfields = explode(',', $contents);

echo $arrfields[0]; 
echo $arrfields[1]; 
echo $arrfields[2]; 

Or, in a loop:

foreach($arrfields as $field) {
    echo $field;
}
Ninju
  • 2,522
  • 2
  • 15
  • 21
0

Another option is using fgetcsv where you don't need to explode the values.

If your csv file uses a different delimiter, simply pass it as a parameter to fgetcsv

Example

$h = fopen("csv.csv", "r");

while (($line = fgetcsv($h)) !== FALSE) {
    print_r($line);
}

fclose($h);
Alex Andrei
  • 7,315
  • 3
  • 28
  • 42