PHP - Parsing a Txt File

PHP - parsing a txt file

You can do that easily this way

$txt_file    = file_get_contents('path/to/file.txt');
$rows = explode("\n", $txt_file);
array_shift($rows);

foreach($rows as $row => $data)
{
//get row data
$row_data = explode('^', $data);

$info[$row]['id'] = $row_data[0];
$info[$row]['name'] = $row_data[1];
$info[$row]['description'] = $row_data[2];
$info[$row]['images'] = $row_data[3];

//display data
echo 'Row ' . $row . ' ID: ' . $info[$row]['id'] . '<br />';
echo 'Row ' . $row . ' NAME: ' . $info[$row]['name'] . '<br />';
echo 'Row ' . $row . ' DESCRIPTION: ' . $info[$row]['description'] . '<br />';
echo 'Row ' . $row . ' IMAGES:<br />';

//display images
$row_images = explode(',', $info[$row]['images']);

foreach($row_images as $row_image)
{
echo ' - ' . $row_image . '<br />';
}

echo '<br />';
}

First you open the text file using the function file_get_contents() and then you cut the string on the newline characters using the function explode(). This way you will obtain an array with all rows seperated. Then with the function array_shift() you can remove the first row, as it is the header.

After obtaining the rows, you can loop through the array and put all information in a new array called $info. You will then be able to obtain information per row, starting at row zero. So for example $info[0]['description'] would be Some text goes here.

If you want to put the images in an array too, you could use explode() too. Just use this for the first row: $first_row_images = explode(',', $info[0]['images']);

PHP parse a .txt

Followed advice of https://stackoverflow.com/users/1552594/mike-miller and swapped from .txt to .csv file. This made everything much easier to run through and solved all errors.

Parsing Text File into Variables with PHP

If you are reading the entire file into an array anyway, then just use file() which will read each line into an array.

$content = file('DC_PictureCalendar/admin/database/cal2data.txt', FILE_IGNORE_NEW_LINES);

You can then filter all the lines you don't want like this

$content = array_diff($content, array('1,1,0', '-'));

You can then break into chunks of 4 lines each (i.e. one item per entry)

$content_chunked = array_chunk($content, 4);

This would give you an array like

Array(
0 => Array(
0 => '7/4/2013-7/4/2013',
1 => 'Best Legs in a Kilt',
2 => 'To start the summer off with a bang, the Playhouse has teamed up with the folks at The Festival.',
3 => 'kilt.jpg'
),
1 => Array(
0 => '7/8/2013-7/23/2013',
1 => 'Hot Legs',
2 => 'Yes, folks, it's all platform shoes, leisure suits, and crazy hair-do's.',
3 => 'hotstuff.jpg'
) ... etc.
)

I would then map this array into a useful array of objects with property names that are meaningful to you:

$items = array_map(function($array)) {
$item = new StdClass;
$item->date = $array[0];
$item->showname = $array[1];
$item->summary = $array[2];
$item->image = $array[3];
return $item;
}, $content_chunked);

That would leave you with an array of objects like:

Array(
0 => stdClass(
'date' => '7/4/2013-7/4/2013',
'showname' => 'Best Legs in a Kilt',
'summary' => 'To start the summer off with a bang, the Playhouse has teamed up with the folks at The Festival.',
'image' => 'kilt.jpg'
),
1 => stdClass(
'date' => '7/8/2013-7/23/2013',
'showname' => 'Hot Legs',
'summary' => 'Yes, folks, it's all platform shoes, leisure suits, and crazy hair-do's.',
'image' => 'hotstuff.jpg'
) ... etc.
)

PHP - Parsing a *.TXT File

Here's a little more description as to how you could do it along with some code that you can modify. Note that this is not a production grade code.

Theory

  • Read file line by line
  • If line begins with (i.e. matches) digits followed by dot followed by space, remember the question in an array as a key
  • If line does not match, remember each line in an answers array
  • When we hit the next line that matches, associated all the answers collected so far to the prior question
  • After looping is done, we may still have an array full of answers. If we do, associate it with the last question we read

At this point we have our quiz questions and answers populated as an associated array that looks like this:

Array
(
[1. What color is the water?] => Array
(
[0] => Red
[1] => *Blue
[2] => Green
[3] => Orange
)

[2. Stack Overflow is awesome.] => Array
(
[0] => *True
[1] => False
)

[3. Explain why you love code:] =>
)

Now we loop through the questions and get whether the answer are of type ES, TF or MC. We also format the answers nicely. And then display it.

Practice

Create a function that reads a file and creates this kind of array for us.

/**
* Get questions and answers from file
*
* @param $filename string Name of the file along with relative or absolute path
*
* @returns array Associated array of 'question1'=>array-of-answers, 'question2'=>array2-of-answers
*/
function getQuestionsAndAnswers($filename)
{
$file = @fopen($filename, 'r');

$quiz = array(); // associated array containing '1. question1'=>answer array
$answers = array(); // temporarily holds answers
$question = ''; // temporarily holds questions

while (($line = fgets($file)) != null)
{
$line = trim($line);
if ($line === '') continue;

if (preg_match('/^\d+\. /', $line) === 1)
{
if (count($answers) > 0)
{
$quiz[$question] = $answers;
$answers = array();
}
$question = $line;
$quiz[$question] = '';
}
else
{
$answers[] = $line;
}
}

if (count($answers) > 0)
{
$quiz[$question] = $answers;
}

return $quiz;
}

Create a function that takes answers and tells us what type of answer that is.

/**
* Get answer type short code from answer array
*
* @param $answer array Answers
*
* @returns string Short code answer type (e.g. ES for Essay, TF for True/False, MC for multiple choice)
*/
function answerType($answer)
{
if (!is_array($answer)) return 'ES';
$flattenedAnswer = implode(',', $answer);
if (stripos($flattenedAnswer, 'true') !== false) return 'TF';
return 'MC';
}

Create a function that formats our answers nicely

/**
* Format answers based on answer type
*
* @param $answer array Answers
* @param $answerType string Short code of answer type
*
* @returns string Formatted answer
*/
function answers($answer, $answerType)
{
if ($answerType === 'ES') return $answer;

if ($answerType === 'TF')
{
foreach ($answer as $x)
{
if (strpos($x, '*') === 0) return substr($x, 1);
}
return '';
}

$flattenedAnswer = '';
foreach ($answer as $x)
{
if (strpos($x, '*') === 0)
{
$flattenedAnswer .= ' ' . substr($x, 1) . ' Correct';
}
else
{
$flattenedAnswer .= " $x Incorrect";
}
}
return $flattenedAnswer;
}

Now that we have our foundational pieces, let's put it all together.

// $quiz will be populated as an array that looks like this
// 'question1'=>array('answer1', 'answer2')
// 'question2'=>array('answer1', 'answer2') etc
$quiz = getQuestionsAndAnswers('./questions.txt');

// loop through all questions and use functions to format the output
foreach ($quiz as $question=>$answer)
{
$answerType = answerType($answer);
echo sprintf("%s %s %s\n",
$answerType,
$question,
answers($answer, $answerType)
);
}

Let's run the code and see the output:

$ php questions.php
MC 1. What color is the water? Red Incorrect Blue Correct Green Incorrect Orange Incorrect
TF 2. Stack Overflow is awesome. True
ES 3. Explain why you love code:

Great. Looks like it all worked out well. I hope the code is self commented, but if you have questions, feel free to ask.

Parse text file with PHP

Organize the content of your text file like this : name1,age2,phonenumber,asd,district

And do this :

// Get the content of your file
$content = file_get_contents('a.text');
// Set your values with this
list($name, $age, $phone, $a, $district) = explode(',', $content);

// Then feel free to echo wathever you want
echo 'Name ' . $name;

Parse txt files and turn them into static html files

You could get the lines from the file one by one, instead of getting the whole file, and then formatting them individually and putting them into variables ready to be echoed out on your page. However, the method proposed by Dontfeedthecode is so far superior and more efficient that I have withdrawn the original and hope that he will approve of what I have done with his idea.

     <?php         
$files = glob("*.txt"); // Scan directory for .txt files

// Check that there are .txt files in directory
if ($files !== false) {
$numberOfFiles = count($files); // Count number of .txt files in directory

// Check if number of files is greater than one
if ($numberOfFiles > 1) {
// Advanced loop will go here to process multiple txt files
} else {

$text_array = array();
$file_handle = fopen ($files[0], "r"); // Open file
$text_array = stream_get_contents($file_handle);
$text_array = explode("\n", $text_array);
// get the top three lines
$page_title = trim($text_array[0]);
$all_lines = '<p>' . trim($text_array[0]) . ' - ' . trim($text_array[1]) . ' - ' . trim($text_array[2]) . '</p>';
// delete the top four array elements
$text_array[0] = $text_array[1] = $text_array[2] = $text_array[3] = '';
// get the remaining text
$text_block = trim(implode($text_array));
fclose ($file_handle); // Close file connection
} // endifs for first if(... statements
}
?>

HTML Output:

         <!DOCTYPE html>
<html>
<head>
<title><?php echo $page_title; ?></title>
</head>
<body>
<?php echo $all_lines . "\n" . '<p>' . $text_block .'</p>'. "\n"; ?>
</body>
</html>

A variable ready to print to file:

<?php
$print_to_file = '<!DOCTYPE html>
<html>
<head>
<title>' . $page_title . '</title>
</head>
<body>' . "\n" . $all_lines . "\n" . '<p>' . $text_block .'</p>'. "\n" .
' </body>
</html>';

echo $print_to_file;
?>

HTML looks a bit displaced in the variable here but comes out right when printed.

And finally, a version which puts a <p> tag for each line of the text.

     <?php
$files = glob("*.txt"); // Scan directory for .txt files

// Check that there are .txt files in directory
if ($files !== false) {
$numberOfFiles = count($files); // Count number of .txt files in directory

// Check if number of files is greater than one
if ($numberOfFiles > 1) {
// Advanced loop will go here to process multiple txt files
} else {

$text_array = array();
$file_handle = fopen ($files[0], "r"); // Open file

$text = stream_get_contents($file_handle);

// get the top three lines
$text_array = explode("\n", $text);
$page_title = trim($text_array[0]);
$all_lines = '<p>' . $text_array[0] . ' - ' . $text_array[1] . ' - ' . $text_array[2] . '</p>';
// set up something to split the lines by and add the <p> tags
$text_array = str_replace("\n","</p>\nxxx<p>", $text);
$text_array = explode("xxx", $text_array);

// delete the top four array elements
$text_array[0] = $text_array[1] = $text_array[2] = $text_array[3] = '';
// get the remaining text

$text_block = trim(implode($text_array));

}
}
?>

This version can use the same html/php blocks as above



Related Topics



Leave a reply



Submit