I"m trying to make a web form that outputs to flat text file line by line what the input to the web form is. Several of the fields are not required but the output file must input blank spaces in for whatever is not filled out. Here is what I'm trying:
$output = $_SESSION["emp_id"];
if(!empty($_POST['trans_date'])) {
$output .= $_POST["trans_date"];
}else{
$output = str_pad($output, 6);
}
if(!empty($_POST['chart'])) {
$output .= $_POST["chart"];
}else{
$output = str_pad($output, 6);
}
write_line($output);
function write_line($line){
$file = 'coh.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new line to the file
$current .= $line . PHP_EOL;
// Write the contents back to the file
file_put_contents($file, $current);
}
However, when I check my output the spaces don't show up. Any ideas on what's going on with this? Thanks in advance!
str_pad is padding with spaces, not adding spaces. You're padding an existing value with spaces so that it is 6 characters long, not adding 6 whitespaces to the value. So if $_SESSION["emp_id"] is 6 characters long or more, nothing will be added.
str_pad() won't add that number of spaces, but rather makes the string that length by adding the appropriate number of spaces. Try str_repeat():
$output = $_SESSION["emp_id"];
if(!empty($_POST['trans_date'])) {
$output .= $_POST["trans_date"];
}else{
$output = $output . str_repeat(' ', 6);
}
if(!empty($_POST['chart'])) {
$output .= $_POST["chart"];
}else{
$output = $output . str_repeat(' ', 6);
}
write_line($output);
function write_line($line) {
$file = 'coh.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new line to the file
$current .= $line . PHP_EOL;
// Write the contents back to the file
file_put_contents($file, $current);
}
Cheers!
Related
This question already has answers here:
RegEx to remove /** */ and // ** **// php comments
(3 answers)
Closed 4 years ago.
I need to delete a particular file content that is between these two characters /* & */ using PHP. The file from which I am trying to remove these comments is very large and includes a large data set, So optimized solution will be appreciated.
Example content:
/*SOME TEXT HERE
*/ 12314
So, the final file should contain only
1234
Here is the method that keeps on running until we got the comments string. Please note that the comments are only at one place in the file and they are always on the top of the file. Please let me know how can I delete those lines on which match the comments condition?
Below is the method that I updated.
$reading = fopen(public_path('file.csv'), 'r');
$writing = fopen(public_path('file.csv'), 'w');
$counter = 0;
$line = "";
$no_of_lines = 0;
while (!feof($reading) && $counter != 2) {
$new_line = fgets($reading);
if ($matched_string = strstr($new_line, "/*")) {
$line = $line . $matched_string;
$counter++;
} elseif ($matched_string = strstr($new_line, "*/")) {
$line = $line . $matched_string;
$counter++;
} else {
$line = $line . $new_line;
fwrite($writing, "");
}
$no_of_lines++;
}
fclose($writing);
fclose($reading);
First open the file but one line at a time to save memory:
<?php
$reading = fopen('myfile', 'r');
$writing = fopen('newfile', 'w');
while (!feof($reading)) {
$line = fgets($reading);
// We will put the removal logic in here
fputs($writing, $line);
}
fclose($reading);
fclose($writing);
For the removal, use some regex.
<?php
$line = preg_replace('#\/\*.+\*\/#', '/* */', $line);
You can see this working here https://3v4l.org/XmltD
If you don't want the /* either, just change the replace call to this:
$string = preg_replace('#\/\*.+\*\/#', '', $string);
I have a text file, called logs.txt, I'm trying to create a script in PHP which is supposed to check if a string which starts with foo|| exists. If it exists, it should be replaced with a specific string, otherwise a specific string will be added at the end of the file.
This is the code I tried to make:
<?php
function replaceInFile($what, $with, $file){
$buffer = "";
$fp = file($file);
foreach($fp as $line){
$buffer .= preg_replace("|".$what."[A-Za-z_.]*|", $what.$with, $line);
}
fclose($fp);
echo $buffer;
file_put_contents($file, $buffer);
}
replaceInFile("foo||", "foo||hello", "logs.txt");
?>
but it doesn't really do what I want. Can someone help me on fixing the code? Any help is appreciated.
This should work:
$newline = preg_replace('/^' . $what . '(.*)$/', $with . '${1}', $line, 1 , $count);
$buffer .= ($count == 1) ? $newline : $line . $with;
The common Delimiters is / no | specially if you have | in your search criteria. Than you have to create a Capturing Group this is between ( and ). Now you can use this Capturing Group and in your replacement as ${ + number of the Capturing Group + }. In your case you only have one.
i tried to search, but still dont know the solution at all, for my next PHP code.
<?php
$city="Budapest"; // Your city
$country="hu"; // Two digit country code
$url="http://api.openweathermap.org/data/2.5/weather?q=".$city.",".$country."&appid=2de143494c0b295cca9337e1e96b00e0&units=metric";
$json=file_get_contents($url);
$data=json_decode($json,true);
$file = '/home/cs2d/sys/lua/weather.dat';
$current = file_get_contents($file);
$current .= $data['weather'][0]['main']."\n".$data['main']['temp']."\n";
// Write the contents back to the file
file_put_contents($file, $current);
?>
As you can see it's a simple code, which write values into the weather.dat file.
But how to possible to do that its just refresh lines instead of add new one.
Any idea?
This works :
$city="Budapest"; // Your city
$country="hu"; // Two digit country code
$url="http://api.openweathermap.org/data/2.5/weather?q=".$city.",".$country."&appid=2de143494c0b295cca9337e1e96b00e0&units=metric";
$json=file_get_contents($url);
$data=json_decode($json,true);
$file = 'weather.dat';
$current = file_get_contents($file);
$contents = file_get_contents($file);
echo $current;
$contents = str_replace($current, ' ', $contents);
echo $contents;
file_put_contents($file,$contents);
$current = file_get_contents($file);
$current .= $data['weather'][0]['main']."\n".$data['main']['temp']."\n";
// Write the contents back to the file
file_put_contents($file, $current);
I am using PHP to read a simple text file with the fgets() command:
$file = fopen("filename.txt", "r") or exit('oops');
$data = "";
while(!feof($file)) {
$data .= fgets($file) . '<br>';
}
fclose($file);
The text file has leading white spaces before the first character of each line. The fgets() is not grabbing the white spaces. Any idea why? I made sure not to use trim() on the variable. I tried this, but the leading white spaces still don't appear:
$data = str_replace(" ", " ", $data);
Not sure where to go from here.
Thanks in advance,
Doug
UPDATE:
The text appears correctly if I dump it into a textarea but not if I ECHO it to the webpage.
Function fgets() grabs the whitespaces. I don't know what you are exactly doing with the $data variable, but if you simply display it on a HTML page then you won't see whitespaces. It's because HTML strips all whitespaces. Try this code to read and show your file content:
$file = fopen('file.txt', 'r') or exit('error');
$data = '';
while(!feof($file))
{
$data .= '<pre>' . fgets($file) . '</pre><br>';
}
fclose($file);
echo $data;
The PRE tag allows you to display $data without parsing it.
Try it with:
$data = preg_replace('/\s+/', ' ', $data);
fgets should not trim whitespaces.
Try to read the file using file_get_contents it is successfully reading the whitespace in the begining of the file.
$data = file_get_contents("xyz.txt");
$data = str_replace(" ","~",$data);
echo $data;
Hope this helps
I currently have the same requirement and experienced that some characters are written as a tab character.
What i did was:
$tabChar = ' ';
$regularChar = ' '
$file = fopen('/file.txt');
while($line = fgets($file)) {
$l = str_replace("\t", $tabChar, $line);
$l = str_replace(" ", $regularChar, $line);
// ...
// replacing can be done till it matches your needs
$lines .= $l; // maybe append <br /> if neccessary
}
$result = '<pre'> . $lines . '</pre>';
This one worked for me, maybe it helps you too :-).
I have an array that I want to export to a CSV file, now I know that there is a fputcsv function but I am using version 5.0.4 of PHP so this isn't an option for me.
Is there an alternative method I can use?
You can use a polyfill for this. write your code as if you where on a system that supports fputcsv From comments within the php block (with some slight framing code) but include this
(copied and slightly modified from http://www.php.net/manual/en/function.fputcsv.php#56827)
<?php
if (!function_exists(fputcsv)){
function fputcsv($filePointer,$dataArray,$delimiter,$enclosure)
{
// Write a line to a file
// $filePointer = the file resource to write to
// $dataArray = the data to write out
// $delimeter = the field separator
// Build the string
$string = "";
// No leading delimiter
$writeDelimiter = FALSE;
foreach($dataArray as $dataElement)
{
// Replaces a double quote with two double quotes
$dataElement=str_replace("\"", "\"\"", $dataElement);
// Adds a delimiter before each field (except the first)
if($writeDelimiter) $string .= $delimiter;
// Encloses each field with $enclosure and adds it to the string
$string .= $enclosure . $dataElement . $enclosure;
// Delimiters are used every time except the first.
$writeDelimiter = TRUE;
} // end foreach($dataArray as $dataElement)
// Append new line
$string .= "\n";
// Write the string to the file
fwrite($filePointer,$string);
}
}
?>
Assuming you have a $Data array, which contains individual arrays for each registry (or line), you may try this:
$Delimiter = '"';
$Separator = ','
foreach($Data as $Line)
{
fwrite($File, $Delimiter.
implode($Delimiter.$Separator.$Delimiter, $Line).$Delimiter."\n");
}
Where $File is the handle for your file. Put in $Delimiter, the character you want to put around each field, and in $Separator, the character to use between fields.
I took the solution from #Orangepill and refactored / simplified it in a couple of ways. This may also become handy if you want every field to be enclosed which is not the case in the default php implementation.
function fputcsv_custom($handle, $fields, $delimiter = ",", $enclosure = '"', $escape_char = "\\") {
$field_arr = [];
foreach($fields as $field) {
$field_arr[] = $enclosure . str_replace($enclosure, $escape_char . $enclosure, $field) . $enclosure;
}
fwrite($handle, implode($delimiter, $field_arr) . "\n");
}