Add text at the benining of a specific line in PHP - php

I would like to know how can I add text at the begining of a specific line in a txt file using PHP.
For example line 2 and 4:
Line 1
Line 2
Line 3
Line 4
to
Line 1
Whatever Line 2
Line 3
Whatever Line 4
Edit: The content of each line is variable all time, so I can't use replace or search for a specific word.
Thank you :)

Get the contents of the file, with each line as an index of the returned array, using file():
$lines = file('path/to/your/file');
Then you can do whatever you need by using the correct line index:
// prepend content to line 2:
$abc = 'abc' . $lines[1];
// append content to line 4:
$xyz = $lines[3] . 'xyz';
The whole process (get the contents, update them, and then replace the original file):
$file = 'yourfile.txt';
$lines = file($file);
$lines[1] = 'xxx' . $lines[1]; // prepend content to line 2.
$lines[3] = 'yyy' . $lines[3]; // prepend content to line 4.
file_put_contents($file, implode('', $lines));"

If you want to add every second line use this code
$n = 0;
for ($i = 1; $i <= 10; $i++) {
if($n % 2 == 1) {
echo "Whatever Line: ".$i."<br>";
} else {
echo "Line ".$i."<br>";
} $n++;
}
but if you want add only second and 4th line use this code.
for ($i = 1; $i <= 10; $i++) {
if(($i == 2) or ( $i == 4)){
echo "Whatever Line: ".$i."<br>";
} else {
echo "Line ".$i."<br>";
}
}

Related

This if condition is false when comparing array to string in PHP

I have a FOR loop and an IF statement that checks each line for a certain word in a txt document. However when the loop gets to a line that holds the value 'header' the IF statement does not think it is true.
txt file
header
bods
#4f4f4f
30
100
1
text
this is content for the page
#efefef
10
300
2
img
file/here/image.png
300
500
filler
3
header
this is header text
#4f4f4f
30
100
4
php file
$order = array();
$e = 0;
$h = 0;
$headerCount = 0;
$textCount = 0;
$imgCount = 0;
//Open file putting each line into an array
$textFile = fopen("test.txt","r+");
$inTextFile = fread($textFile, filesize("test.txt"));
$arrayFile = explode("\n", $inTextFile);
$arrayFileSize = sizeof($arrayFile);
$elementCount = $arrayFileSize / 6;
for ($x = 0; $x < $arrayFileSize; $x++) {
if ($arrayFile[$x] == "header") {
echo $x;
echo " Yes : ".$arrayFile[$x] . "<br>";
$headerCount++;
}
else {
echo $x;
echo " No : " . $arrayFile[$x] . "<br>";
}
}
Welcome to Stack Overflow Billy. There are two solutions you can try: using the trim() function of strpos().
Using trim() will remove any leading or trailing spaces from a string:
if (trim($arrayFile[$x]) == "header") {...}
Using strpos() can help you check if word "header" exists anywhere in a string. If the given word does not exists than it will return false:
if (strpos($arrayFile[$x], "header") !== false) {...}

PHP - Storing text from fopen and fgets into a variable?

$ln = 0;
$start = 0;
$end = 3;
$fd = fopen("output/test.txt", 'r'); // open the file
while(true) {
$line = fgets($fd); // read next line
if(!$line || $ln === $end + 1) {
break;
}
if($ln >= $start && $ln <= $end) {
echo $line;
}
$ln++;
}
fclose($fd); // close the file
Hello, I am trying to grab text off different lines and then turn them into a variable.
Text file:
1. One
2.
3.
4.
5. Two
6.
7.
8.
9.
10.
-----------------------------
But I am having a problem, I want to store the code into a variable to maybe put into a database in the future.
So I want to have each one to be a variable.
So I can then do:
echo $ONE
echo $TWO
I hope you understand me and can help me out.
So to clarify, $ONE would echo line 1. and $TWO would echo line 2

PHP remove extra delimiters from .csv

I want to write a code to remove extra delimiters for each row for a .csv file. With another code i have already determined that the .csv file only contains rows with too many delmiters. I further know which column (after nth delimiter) has extra delimiters. I have already written most of the code, but it's not working yet. Help is very much appreciated.
My PHP skills are still basic.
<?php
$delimiter = ';'; //type delimiter
$delimiter_start_column =23; //column-to-be-cleaned starts after this delimiter
$exp_delimiter =63; //expected delimiters per row
$total_delimiter =substr_count($line,$delimiter); //total delimiters in row
$delimiter_end_column =($exp_delimiter - $delimiter_start_column) + ($total_delimiter - $exp_delimiter); //column-to-be-cleaned ends before this delimiter
function splitleft($line,$delimiter,$delimiter_start_column){
$max = strlen($line);
$n = 0;
for($i=0;$i<$max;$i++){
if($line[$i]==$delimiter){
$n++;
if($n>=$delimiter_start_column){
break;
}
}
}
$arr[] = substr($line,0,$i);
return $arr;
}
function splitright($line,$delimiter,$delimiter_end_column){
$max = strlen($line);
$n = 0;
for($i=0;$i<$max;$i++){
if($line[$i]==$delimiter){
$n++;
if($n>=$delimiter_end_column){
break;
}
}
}
$arr[] = substr($line,$i,$max);
return $arr;
}
// determine start time in microseconds for runtime calculation
$file['datestamp'] = date("Y-m-d_H-i-s", $start);
$input['folder'] = 'input\\';
$input['file'] = ''; //enter filename
$output['folder'] = 'output\\';
$output['file_cleaned'] = $file['datestamp'].'_cleaned_';
// open input file read-only
$handle['input'] = #fopen($input['folder'].$input['file'], "r");
// initialize line, clean and dirty counters
$counter['total'] = 0;
$counter['cleaned'] = 0;
if($handle['input']) {
// open output files. set point to end of file.
$handle['cleaned'] = #fopen($output['folder'].$output['file_cleaned'].$input['file'], "a");
while(($line = fgets($handle['input'])) !== false) {
// increment line counter
$counter['total']++;
$result = substr_count($line, $delimiter);
if($result == $exp_delimiters AND $counter['line'] != 1 AND $line != $header) {
// if the number of delimiters matches the expected number as represented by $exp_delimiters
// increment clean lines counter
$counter['cleaned']++;
$output_file = $handle['cleaned'];
}
else {
// else, if the number of delimiters does not match the expectation
// remove extra delmiters from column
$line_cleaned = splitleft + str_replace(";","",substr($line,strlen(splitleft()),(strlen($line)-strlen(splitleft())-strlen(splitright()))) + splitright());
$output_file = $handle['cleaned'];
}
// prefix line number
$line = $counter['total'].$delimiter.$line;
// write line to correct output file
fwrite($output_file, $line_cleaned);
// output progress every 20.000 processed lines
if($counter['total'] % 20000 == 0) {
echo number_format($counter['total'], 0, ',', '.')."\r\n";
}
}
if(!feof($handle['input'])){
echo "Error: unexpected fgets() fail\n";
}
// close all input and output files
foreach($handle AS $close) {
fclose($close);
}
}
?>

Finding syntax-error in a file that have a custom format using RexEx

I have a big text file (144000 line) that have a custom format like following:
xxx
XXXfield1XXX
value1
xxx
xxx
XXXfield2XXX
value2
xxx
xxx
XXXfield3XXX
value3
xxx
But there is a syntax-error (perhaps more) in the file (Because total line number of file is not dividable to four)
How can I find the line number of error using just RegExp?
Detecting Error is easy .. Imagine
log.txt
xxx
XXXfield1XXX
value1
xxx
xxx
XXXfield2XXX <----- Note that this field has no value
xxx
xxx
XXXfield3XXX
value3
xxx
value3
xxx
Simple Scanner
$fileSource = "log.txt";
$tagRow = "xxx";
$tagField = "XXX";
$rh = fopen($fileSource, 'rb');
if (!$rh) {
trigger_error("Can't Start File Resource");
}
echo "<pre>";
$i = 0;
while ( ! feof($rh) ) {
$l = trim(fgets($rh));
if ((($i % 4) == 0 || ($i % 4) == 3) && $l != $tagRow) {
echo "Row tag error line $i \n";
break;
}
if (($i % 4) == 1 && strpos($l, $tagField) !== 0) {
echo "Missing Field tag line $i \n";
break;
}
if (($i % 4) == 2 && (strpos($l, $tagRow) === 0 || strpos($l, $tagRow) === 0)) {
echo "Fixed Missing Value line $i \n";
break;
}
$i ++;
}
fclose($rh);
Output
Fixed Missing Value line 6
Write a program to read the file, one line at a time, and parse it. If a line isn't consistent with the format, then report the error and exit.
As you read each line, keep track of the line number. Base your tests on the line number using the % operator and a switch statement.
switch ($linecount % 4) {
case 0:
$error = (some condition that evaluates the line);
break;
case 1:
$error = (some condition that evaluates the line);
break;
case 2:
$error = (some condition that evaluates the line);
break;
case 3:
$error = (some condition that evaluates the line);
break;
}
if ($error) {
echo 'Error on line ' . $linenum . ': ' . $line;
exit;
}

how to leave out blank rows using fgetcsv

I have been working on importing a csv file into a mysql database. Problem is my client gets the files already with some bad formatting. the rows end at 43 but the file goes down to 65078!!
When importing, the script takes forever. What can I do to make sure just the rows from 0 to 44 get imported? Here's the code i'm using.
<table>
<?php
//fgetcsv($handle, 1024, delimiter)
$file = fopen("prices.csv", "r");
$row = 0;
while($csv_line = fgetcsv($file,1024)) {
if($row == 4){
echo "How many headers do we have: ".count($csv_line)."<tr>";
foreach($csv_line as $header){
if($header !== NULL){
print "<td>$header</td>";
}
}
echo "</tr>";
}
if($row > 6) {
echo '<tr>';
for ($i = 0, $j = count($csv_line); $i < $j; $i++) {
echo '<td>'.$csv_line[$i].'</td>';
}
echo "</tr>\n";
} else {
$row++;
}
}
?>
</table>
If the number of filled rows isn't fixed, you can use similar approach with:
if (empty($line)) { break; }
Your comment give me an idea for a better solution:
Here http://php.net/manual/en/function.fgetcsv.php appears this "A blank line in a CSV file will be returned as an array comprising a single null field" so maybe this helps:
while(($csv_line = fgetcsv($file,1024)) && $csv_line[0]) {
Will read only until finds an empty row.
Add a if ($row >= 44) { break; } at the bottom of the loop so it'll exit once you reach row 44.

Categories