user1743737
user1743737

Reputation: 45

How to read a text file with PHP?

I have a text file named Se7enPlug.dspl. In this file I have only one line of text, formatted like this:

text1,text2,text3

I need to read this file and return something like this:

public function rconGetNextMap() {

    $myFile = "E:\mw3-server\admin\Se7enPlug.dspl";
    $fh = fopen($myFile, 'r');
    $theData = fread($text1,$text2,$text3);
    fclose($fh);
    echo $theData;

    if ($theData) {

        $next = array("map" => $text1, "gametype" => $text2, 0=>$text1, 1=>$text2);
    }
    elseif (!$theData)) {

        $next = array("map" => "Unknown", "gametype" => "Unknown", 0=>"Unknown",1=>"Unknown");
    }
    return $next;
}

As you see its has many problems. How can I fix it?

Upvotes: 0

Views: 199

Answers (2)

ComFreek
ComFreek

Reputation: 29424

Better use fgetcsv() as Dagon stated:

public function rconGetNextMap() {
  $myFile = '...';
  $handle = fopen($myFile, 'r');
  $retArray = array(
    'map' => 'Unknown',
    'gametype' => 'Unkown',
  );

  if (!$handle) {
    return $retArray;
  }

  $data = fgetcsv($handle, 1000, ',', '"');

  if ($data !== false) {
    $retArray['map'] = $data[0];
    $retArray['gametype'] = $data[1];
  }
  fclose($handle);
  return $retArray;
}

I have removed the two numerical indices from the output array. I wouldn't recommend them because they represent redundant data. But you can easily add them.

Upvotes: 1

Errol Fitzgerald
Errol Fitzgerald

Reputation: 3008

This will read in your text file and save the first and second values into the array

<?php

    $myFile = "E:\mw3-server\admin\Se7enPlug.dspl";
    $fh = fopen($myFile, 'r');
    $theData = fgetcsv($fh,$delimiter = ',');

    if ($theData) {

        $next = array("map" => $theData[0], "gametype" => $theData[1]);
    }

?>

Upvotes: 3

Related Questions