PHP - parsing a txt file - php

I have a .txt file that has the following details:
ID^NAME^DESCRIPTION^IMAGES
123^test^Some text goes here^image_1.jpg,image_2.jpg
133^hello^some other test^image_3456.jpg,image_89.jpg
What I'd like to do, is parse this ad get the values into a more readable format, possibly into an array if possible.
Thanks

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']);

Use explode() or fgetcsv():
$values = explode('^', $string);
Or, if you want something nicer:
$data = array();
$firstLine = true;
foreach(explode("\n", $string) as $line) {
if($firstLine) { $firstLine = false; continue; } // skip first line
$row = explode('^', $line);
$data[] = array(
'id' => (int)$row[0],
'name' => $row[1],
'description' => $row[2],
'images' => explode(',', $row[3])
);
}

By far the best and simplest example of this I have come accross is quite simply the file() method.
$array = file("myfile");
foreach($array as $line)
{
echo $line;
}
This will display all the lines in the file, this is also applicable for a remote URL.
Simple and clear.
REF : IBM PHP Parse

I would like to contribute a file that provides atomic data structures.
$lines = file('some.txt');
$keys = explode('^', array_shift($lines));
$results = array_map(
function($x) use ($keys){
return array_combine($keys, explode('^', trim($x)));
},
$lines
);

Try fgetcsv() with ^ as the separator character:
$file = fopen($txt_file,"r");
print_r(fgetcsv($file, '^'));
fclose($file);
http://www.w3schools.com/php/func_filesystem_fgetcsv.asp

<?php
$row = 1;
if (($handle = fopen("test.txt", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "^")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>

Ok, didn't see the edited version, so here's a redo. It's most likely a CSV file that uses carets as the separator, so...
$fh = fopen('yourfile.txt');
$headers = fgetcsv($fh, 0, '^');
$details = array();
while($line = fgetcsv($fh, 0, '^')) {
$details[] = $line;
}
fclose($fh);

youse a list, and split the "image_1.jpg,image_2.jpg" after you explode the string:
list($number, $status, $text, $images) = explode("^", $data);
$splited_images= preg_split(',', $images);

My solution
function parseTextFile($file){
if( !$file = file_get_contents($file))
throw new Exception('No file was found!!');
$data = [];
$firstLine = true;
foreach(explode("\n", $file) as $line) {
if($firstLine) {
$keys=explode('^', $line);
$firstLine = false;
continue;
} // skip first line
$texts = explode('^', $line);
$data[] = array_combine($keys,$texts);
}
return $data;
}

Related

How to split a php array into several parts to insert them in csv column names?

I wrote a code that allows me to read an excel file, transform it into csv and make modifications on it. I add at the end of this file 10 columns, the problem is that the name of the columns is added at once with "PICT1;PICT2; PICT3;PICT4;..." in only one column at the end of the 10. I would like each column to be called PICT1, PICT2, PICT3... How do I do this?
Currently I have this:
I would like that:
<?php
function multiSplit($string)
{
$output = array();
$cols = explode(",", $string);
foreach ($cols as $col)
{
$dashcols = explode("-", $col);
$output[] = $dashcols[0];
}
return $output;
}
//Modifications on csv file
$delimiter = $delimiterpost;
$csv_data = array();
$row = 1;
if (($handle = fopen($nomcsv, 'r')) !== FALSE) {
while (($data = fgetcsv($handle, 10000, $delimiter)) !== FALSE) {
//Add columns at the end
$data['Pictures Names'] = (!empty($data[4]) ? ($data[7] ?: '') . "_" . $data[4] . '.jpg' : '');
$data['Color-Description'] = (!empty($data[3]) ? (ltrim($data[4], '0') ?: '') . "-" . $data[3] : '');
$out = multiSplit($data[23]);
$data['PICT1'] = $out[0];
$data['PICT2'] = $out[1];
$data['PICT3'] = $out[2];
$data['PICT4'] = $out[3];
$data['PICT5'] = $out[4];
$data['PICT6'] = $out[5];
$data['PICT7'] = $out[6];
$data['PICT8'] = $out[7];
$data['PICT9'] = $out[8];
$data['PICT10'] = $out[9];
// Delete three columns
unset($data[1]);
unset($data[2]);
unset($data[3]);
//Modifications on the fourth line
if ($row == 4)
{
//All uppercase
$data = array_map('strtoupper', $data);
$data = str_replace(' *', '', $data);
$data = str_replace('/', '', $data);
//Replacement of spaces by an underscore
$data = str_replace(' ', '_', $data);
$data = str_replace('__', '_', $data);
//Replacement name by another name
$data = str_replace('STYLE_COLOR.JPG', 'PICT', $data);
$data = str_replace('COLOR-DESCRIPTION', 'COLOR_DESCRIPTION', $data);
array_filter($data, function($value) { return !is_null($value) && $value !== ''; });
for ( $i=1; $i<=10; $i++ ){
$data[] = "PICT$i";
}
}
if ($data[22])
{
$data = str_replace(',', '§- ', $data);
}
$csv_data[] = $data;
$row++;
}
fclose($handle);
}
$csv_data = array_slice($csv_data, 3); // this will remove first three elements
array_pop($csv_data);// this will remove last element from array
if (($handle = fopen($nomcsv, 'w')) !== FALSE) {
foreach ($csv_data as $data) {
fputcsv($handle, $data, $delimiter);
}
fclose($handle);
}
Replace
$data[] ='PICT1'.$delimiter.'PICT2'.$delimiter.'PICT3'.$delimiter.'PICT4'.$delimiter.'PICT5'.$delimiter.'PICT6'.$delimiter.'PICT7'.$delimiter.'PICT8'.$delimiter.'PICT9'.$delimiter.'PICT10';
With a loop that creates the additional array items
// clean out any empty titles as there appear to be some at the end of the array
array_filter($data, function($value) { return !is_null($value) && $value !== ''; });
for ( $i=1; $i<=10; $i++ ){
$data[] = "PICT$i";
}

php how to get whole line after spicific character from text file?

I have text file
name,name1
willhaveishere1
name,name2
willhaveishere2
name,name3
willhaveishere3
i want read it and return like that
$nn = name1
$ss = willhaveishere1
with my code i get only name1
my code is
$file1 = "file.txt";
$file = file($file1);
$count = count($file);
if($count > 0) {
$i = 1;
foreach($file as $row) {
$n = strstr($row, 'name,');
$cc = array("name,");
$dd = array("");
$nn = str_replace($cc, $dd, $n);
echo $nn;
$i++; } }
This is probably what you need
if($count > 0) {
foreach($file as $row) {
$pos = strpos($row, ',');
if($pos !== false){
echo substr($row, $pos + 1);
$nn[] = substr($row, $pos + 1);
} else {
echo $row;
$ss[] = $row;
}
}
}
EDIT
Yes, just loop through, but make sure both $nn and $ss has same count, which is depending on your file.
Also Note: mysql_* functions has been deprecated, so please use mysqli or PDO instead
$count = count($nn);
for($i=0; $i < $count; $i++){
$sql = "INSERT INTO users(name, line) VALUES('$nn[$i]', '$ss[$i]')"; mysql_query($sql);
}
EDIT 2
try this example:
$file = array(
0 => 'name,name1',
1 => 'willhaveishere1',
2 => 'name,name2',
3 => 'willhaveishere2',
4 => 'name,name3',
5 => 'willhaveishere3'
);
$count = count($file);
if($count > 0) {
foreach($file as $row) {
$pos = strpos($row, ',');
if($pos !== false){
$nn[] = substr($row, $pos + 1);
} else {
$ss[] = $row;
}
}
}
echo '<pre>';
$count = count($nn);
for($i=0; $i < $count; $i++){
$sql = "INSERT INTO users(name, line) VALUES('$nn[$i]', '$ss[$i]');";
echo $sql.PHP_EOL;
}
You can try this straightforward method:
if($fh = fopen("file.txt","r")){
$nameBefore = false;
//loop through every line of your file
while (!feof($fh)){
$line = fgets($fh);
//check if the name was detected in previous line
if ($nameBefore !== false)
{
//you have the set of name and line, do what you want
echo $nameBefore . ': ' . $line . '<br />';
$nameBefore = false;
}
else
{
//see if the line is made of two coma separated segments and the first one is 'name'
//Remember the name for the next line
$parts = explode(',', $line);
if (count($parts) == 2 && $parts[0] == 'name')
$nameBefore = $parts[1];
}
}
fclose($fh);
}
One option is to use strpos to find the first occurrence of the character in the line, and if found remove everything from the line before that position. This way you are left with only the part of the line you are interested in.
Code:
$character = ',';
$fileHandle = fopen('file.txt', 'r');
while (!feof($fileHandle)) {
// Retrieve the line from the file
$line = fgets($fileHandle);
// If the line contains the character
// Remove everything before the character
$charPos = strpos($line, $character);
if ($charPos !== false) {
$line = substr($line, $charPos + 1);
}
// Do something with the remainder of the line
echo $line . PHP_EOL;
}
fclose($fileHandle);
Output:
name1
willhaveishere1
name2
willhaveishere2
name3
willhaveishere3
If you wish to retrieve the following line, simply do another retrieve line call in your loop:
while (!feof($fileHandle)) {
// Retrieve two lines in one loop iteration
$lineOne = fgets($fileHandle);
$lineTwo = fgets($fileHandle);
}
Making sure to only apply the comma replace part on the first line. This can lead to problems though if your data is... inconsistent.
Hope this helps.

take special lines from txt database PHP

I have text database
0,Apple,Green
1,Banana,Yellow
2,Cherry,Red
and when I call getdata.php?row=2 I need get data which is 2,cherry,red
I am a bachelor in PHP and I have only one example ,
please help me for this problem.
thanks
$file_handle = fopen("./news.txt", "rb");
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
$parts = explode(',', $line_of_text);
print $parts[0] . $parts[1] . $parts[2];
}
fclose($file_handle);
This would work and would also stop reading as soon as it found the right line (unlike the other answers who read the whole no file matter what)
if (isset($_GET['row']))
{
$file_handle = fopen("./news.txt", "rb");
$i = 0;
while (!feof($file_handle))
{
if ($i == $_GET['row'])
{
$line_of_text = fgets($file_handle);
$parts = explode(',', $line_of_text);
print $parts[0] . $parts[1] . $parts[2];
break;
}
$i++;
}
fclose($file_handle);
}
You first have to explode by rule with explode("/n", $txt) than you've an array of each rule. After you stored this explode in to a variable than you should explode a specific value again by ,.
A straightforward way to do this: if record number 2 is always on line number 3.
if (!isset($_GET['row']) || !is_int($_GET['row'])) {
echo "please supply a row number";
die;
}
$lines = file('news.txt');
// assumes record number 2 is on line 3
$row = $_GET['row'] + 1;
$parts = explode(',', $lines[$row]);
print $parts[0] . $parts[1] . $parts[2];
If record number 2 is not guaranteed to be on line 3
$row = $_GET['row'];
foreach ($lines as $line) {
if (strpos($line, $row) === 0) {
$parts = explode(',', $lines[$row]);
print $parts[0] . $parts[1] . $parts[2];
break;
}
}
If the file is extremely large you will want to read line by line from a buffer.
$row = $_GET['row'];
if ($fp = fopen('news.txt', 'r')) {
while ($line = fgets($fp)) {
if (strpos($line, $row) === 0) {
$parts = explode(',', $line);
print $parts[0] . $parts[1] . $parts[2];
break;
}
}
fclose($fp);
}

How to echo array elements that contain a variable —PHP

I have a script that looks through a file and returns every newline as an array element.
$file = fopen("dict.txt", "r");
$entries = array();
while (!feof($file)) { $entries[] = fgets($file); }
fclose($file);
I also have a script which does some utilities with a $_GET variable.
$word = htmlspecialchars($_GET["user"]);
$letters = $word[0] . $word[1] . $word[2];
What I would like to do now is to echo all elements in the $entries array beginning with $letters.
Any help would be much appreciated.
try
foreach($entries as $entry) {
if (strpos($entry, $letters) === 0) {
echo $entry;
}
}

PHP: Splitting a string and printing

I have server output that looks like this
PLAYER_ENTERED name ipaddress username
If the string contains PLAYER_ENTERED there will always be 3 spaces within the string separating it (how can this be modified so it does this too?). I would like to print out only the ipaddress and username (last 2 sections).
How can this be done?
This is code that prints out the whole thing:
$q = $_REQUEST["ipladder"];
$f = fopen("ladderlog.txt", "r");
while (($line = fgets($f)) !== FALSE)
{
if (strstr($line, $q))
{
print "<li>$line";
}
I imagine this using explode() but I've given up trying since I hardily know how to code php.
Desired Output
username ipaddress
$q = $_REQUEST["ipladder"];
$f = fopen("ladderlog.txt", "r");
while (($line = fgets($f)) !== FALSE)
{
if (strstr($line, $q))
{
$data = explode(" ", $line); // split using the space into an array
// array index 0 = PLAYER_ENTERED
print "IP:" . $data[1]; // array index 1 = IP
print "Name: " . $data[2]; // array index 2 = name
}
}
You can use substr()to check if the first 14 characters of $line equals PLAYER_ENTERED and then you use list() and explode() to extract the data from the line.
$q = $_REQUEST["ipladder"];
$f = fopen("ladderlog.txt", "r");
while(($line = fgets($f)) !== FALSE)
{
if(substr($line, 0, 14) == 'PLAYER_ENTERED'){
list($event, $name, $ip, $username) = explode($string); // here they come!
echo 'Name: ' . $name . ', ip: ' . $ip . ', username: ' . $username;
}
}
try this ...
<?
$str = "PLAYER_ENTERED name 108.21.131.56 username";
if ( preg_match( "~^(.+)\s+(.+)\s+([\d\.]+)\s+(.+)$~msi", $str, $vv ))
echo $vv[3] . " and " .$vv[4] ;
else "N/A";
?>
IMHO Perl regexp - is the right Way to parse strings ...
One way would be:
$tokens = explode(' ', $line);
if (count($tokens) == 4 && $tokens[2] == $q) {
printf('IP: %s Username: %s', $tokens[2], $tokens[3]);
}
<?php
$str = 'PLAYER_ENTERED name 108.21.131.56 username';
$data = explode(" ", $str )
print_r($data)
?>

Categories