input.txt
just some example text, just some example text
some example text
example text, just some example text
$inFile = "input.txt";
$outFile = "output.txt";
$data = array();
$ftm = fopen($outFile, "w+");
$fh = fopen($inFile, "r");
$data = file($inFile);
foreach ($data as $key => $value)
{
$row = $value;
$str_length = strlen($row);
if ($str_length > 10)
{
$width = strlen($row)/2;
$wrapped = wordwrap($row, $width);
fwrite($ftm, $wrapped);
}
else
{
fwrite($ftm, $row);
}
}
fclose($fh);
How can I add a newline \n to the center position of each line?
//Related:
$wrapped = wordwrap($row, $width, '\N');
I'm not sure if this is what you're expecting, but it works given supplied text:
just some example text
some example text
example text
which results to a written file as: (if using '\n')
just some\nexample\ntext
some\nexample\ntext
example\ntext
(EDIT) and as:
just some
example
text
some
example
text
example
text
(if using "\n") which will result having no spaces at the end of each line.
PHP
<?php
$inFile = "input.txt";
$outFile = "output.txt";
$data = array();
$ftm = fopen($outFile, "w+");
$fh = fopen($inFile, "r");
$data = file($inFile);
foreach ($data as $key => $value)
{
$newline = "\n"; // writes to file with no spaces at the end of each line
// $newline = '\n'; // use single quotes if wanting to write \n in the file
$row = $value;
$str_length = strlen($row);
if ($str_length > 10)
{
$width = strlen($row) / 2;
$wrapped = wordwrap($row, $width, $newline);
fwrite($ftm, $wrapped);
}
else
{
fwrite($ftm, $row);
}
}
fclose($fh);
Related
$my_content = "This is the first line\n
This is the second line\n
This is the third line\n";
$my_filename = "save.txt";
function file_writer(string $file_to_write, string $content_to_write){
$file = fopen($file_to_write, "w") or die("Unable to open file");
file_put_contents($file_to_write, $content_to_write);
fclose($file);
}
file_writer($my_filename, $my_content);
function file_reader(string $file_to_read, int $num_lines) {
$file = fopen($file_to_read, "r");
while(! feof($file))
{
$line = fgets($file);
echo $line;
}
}
**file_reader($my_filename, 3);**
Try this:
function file_reader(string $file_to_read, int $num_lines) {
$file = fopen($file_to_read, "r");
$c = 0;
while(! feof($file) && $c != $num_lines)
{
$c = $c+1;
$line = fgets($file);
echo $line;
}
}
Your other problem is that you have newlines after newlines.
$my_content = "This is the first line\nThis is the second line\nThis is the third line\n";
function file_reader(string $file_to_read, int $num_lines) {
$file = fopen($file_to_read, "r");
$currLineNo = 1;
while(!feof($file) && (currLineNo < $num_lines))
{
$line = fgets($file);
echo $line;
$currLineNo += 1;
}
}
Havent tried the code myself. This is roughly way you can stop the loop at arbitrary line number.
i wrote a convert bulk data from an excel to a .txt or .csv by using fwrite php. however when I fread on the .txt file that my data placed on, the data turned out broken line. how can i fix it? Attached here is the highlighted from .txt or .csv and also the codes as below:-
**********my write code *************
for loop here {
$split_filename_path = fopen($tempfile_path.$split_filename.$total_round.$extension, "w");`
$split_file_txt = $ISBN.$comma.$Title.$comma.$Qty.$comma.$Location.$comma.$outlet;
fwrite($split_filename_path, $split_file_txt);
}
fclose($split_filename_path);
then it comes here
my read code*****
$myfile = fopen($file, "r");
$fread = fread($myfile,filesize($file));
fclose($myfile);
$split = explode("\n",$fread);
$datafields = array('ISBN', 'title', 'qty', 'location', 'outlet');
$insertvalues = array();
foreach($split as $string){
$row = explode(",",$string);
$questionmarks[] = '(' . $this->placeholder('?',$irow, sizeof($row)) . ')';
$insertvalues = array_merge( $insertvalues, array_values($row));
}
$sql = "INSERT INTO temp_data (".implode( ',', $datafields) . ")
VALUES ". implode( ',', $questionmarks);
function placeholder( $text, $irow, $count = 0, $separator = ',' ) {
$result = array();
if ($count > 0) {
for ($x = 0; $x < $count; $x++) {
$result[] = $text;
}
}
return implode($separator, $result);
}
with this codes, the result that I have is here :
9780794435295,BARBIE & HER SISTERS IN THE GREAT PUPPY ADVENTURE: (supposed to be full :- BARBIE & HER SISTERS IN THE GREAT PUPPY ADVENTURE: A SLIDING TAB BOOK BARBIE MOVIE TIEIN )
found the answer.
$Title = preg_replace( "/\r|\n/", "", $Title);
I want to remove blank line from this text file :
test1
test2
test3
test4
So I try this code in PHP :
$file = __DIR__.$namefile;
foreach ($file as $k => $v) {
if (!trim($v))
unset($lines[$k]);
}
$f = fopen($file, "r");
$array1 = array();
//Extract all url from file
while ( $line = fgets($f, 1000) ) {
$nl = mb_strtolower($line,'UTF-8');
$array1[] = $nl;
}
But it does not work. Thanks for your help !
How about exploding each new line and checking if it's empty?
<?php
$content = fopen($file = __DIR__.$namefile, "r");
$lines = explode("\n", $content);
$result = array();
foreach ($lines AS $line) {
if (!empty($line)) {
$result[] = $line;
}
}
$result = implode("\n", $result);
Or, as Henders suggests, look at https://stackoverflow.com/a/7972266/1441858:
<?php
$content = fopen($file = __DIR__.$namefile, "r");
$lines = explode("\n", $content);
$result = array_filter($lines, 'trim');
$result = implode("\n", $result);
$file = __DIR__.$namefile;
$f = fopen($file, "r");
$array1 = array();
//Extract all url from file
while ( $line = fgets($f, 1000) ) {
$nl = mb_strtolower($line,'UTF-8');
if (trim($line) != "") {
$array1[] = $nl;
}
}
fclose($f);
$file = __DIR__.$namefile;
$lines = explode("\n", file_get_contents($file));
$result = array_filter($lines);
echo implode("\n", $result);
file_put_contents($file, implode("\n", $result)); //save
Or use:
$result = array_filter($lines, 'trim');
If there can be whitespaces in blank lines.
I am trying to add a string to the end of eachline. So far this works. However I dont want the string to be added to the end of the first line. How can I do this?
So far i have got:
<?php
$EOLString="string \n";
$fileName = "file.txt";
$baseFile = fopen($fileName, "r");
$newFile="";
while(!feof($baseFile)) {
$newFile.= str_replace(PHP_EOL, $EOLString, fgets($baseFile));
}
fclose($baseFile);
file_put_contents("newfile.txt", $newFile);
$bingName = "newfile.txt";
$bingFile = fopen($bingName, "a+");
fwrite($bingFile,$EOLString);
fclose($bingFile);
?>
I have also tried to loop it by doing this:
<?php
$EOLString="string \n";
$fileName = "file.txt";
$baseFile = fopen($fileName, "r");
$newFile="";
$x = 0;
while(!feof($baseFile)) {
if ($x > 0) {
$newFile.= str_replace(PHP_EOL, $EOLString, fgets($baseFile));
}
$x++;
}
fclose($baseFile);
file_put_contents("newfile.txt", $newFile);
$bingName = "newfile.txt";
$bingFile = fopen($bingName, "a+");
fwrite($bingFile,$EOLString);
fclose($bingFile);
?>
So the end result would look like:
firstonestring
secondonestring
thirdonestring
and so on.
I hope you can help me!
Ben :)
Just add a counter to your loop:
$counter = 0;
while(!feof($baseFile)) {
$line = fgets($baseFile)
if($counter++ > 0){
$newFile.= str_replace(PHP_EOL, $EOLString, $line);
}else{
$newFile.= $line . "\n";
}
}
Also, you seem to be writting the new file, only to reopen it and append more data. There is no need to do that, just append to the contents before you write it the 1st time:
fclose($baseFile);
file_put_contents("newfile.txt", $newFile . $EOLString);
//$bingName = "newfile.txt";
//$bingFile = fopen($bingName, "a+");
//fwrite($bingFile,$EOLString);
//fclose($bingFile);
Alternativly, you can just read in the whole file, split into lines, and rejoin:
$EOLString="string \n";
$lines = explode("\n", file_get_contents("file.txt"));
$first = array_shift($lines);
file_put_contents("newfile.txt", $first . "\n" . implode($EOLString, $lines) . $EOLString);
//done!
By using a flag
$first = TRUE;//set true first time
while (!feof($baseFile)) {
$line = fgets($baseFile);
if (!$first) {// only enter for false
$newFile.= str_replace(PHP_EOL, $EOLString, $line);
}
$first = FALSE;// set false except first
}
I am learning PHP and files and I am trying to write some code that put data in a binary file.
here's my code:
Write
<?php
echo "\n\nWRITE: \n\n";
$c = array();
$data = '';
$c['name'] = 'abcdefghijklmnopqrstuvwxyz';
$data .= implode('', $c);
$fp = fopen('test.bin', 'wb');
$len = strlen($data);
echo "\nFILE CONTENT: $data (strlen: $len)\n\n";
for ($i = 0; $i < $len; ++$i) {
$hx = dechex(ord($data{$i}));
fwrite($fp, pack("C", $hx));
}
echo "Last char is: $hx which mean: ";
echo chr(hexdec('7a'));
echo "\n--------------------------------------------\n";
fclose($fp);
Output
FILE CONTENT: abcdefghijklmnopqrstuvwxyz (strlen: 26)
Last char is: 7a which mean: z
Read
<?php
echo "\n--------------------------------------------\n";
echo "\n\nREAD: \n\n";
$fp = fopen('test.bin', 'rb');
$fseek = fseek($fp, 0, SEEK_SET);
if($fseek == -1) {
return FALSE;
}
$data = fread($fp, 26);
$arr = unpack("C*", $data);
$return = '';
foreach($arr as $val) {
$return .= chr(hexdec($val));
}
$n = '';
$arr = array();
$arr['name'] = substr($return, 0, 26);
print_r($arr);
echo "\n--------------------------------------------\n";
Output
Array
(
[name] => abcdefghipqrstuvwxy
)
Where are the missing letters like the z, m, n or o ?
EDIT 6-3-14 7h36 am: I would like to have the .bin file not plain text if possible
You are trying to set HEX chars in a char (C - unsigned char) instruction.
echo "\t";
foreach( array('0x41', 65, 'a') as $o )
echo $o."\t";
echo "\n";
foreach( array('c*','C*','a*','A*','h*','H*','v*','n*','S*') as $o ){
echo $o . "\t";
foreach( array(0x41, 65, "a") as $oo ) {
echo pack($o, $oo);
echo "\t";
}
echo "\n";
}
If you run this, you will see quickly how pack works with the 3 different values of a (HEX, DEC and normal).
You have to use the h instruction to accomplish what you need.
function writeToFile($data) {
$fp = fopen(FILENAME, 'wb');
$len = strlen($data);
for ($i = 0; $i < $len; ++$i) {
$hx = dechex(ord($data[$i]));
$result = fwrite($fp, pack("h*", $hx));
if(!$result) {
// show something
}
}
fclose($fp);
}
Now, for read that data. You will need to use the same one h and split the string you get back (split it using str_split with the parameter 2 since it's HEX 00 = 0 and FF = 255 - assuming you won't go over 255). Since h returns an array with a single element. Once you get your string back, you need to convert the number you get from the ord in the writeToFile using the chr function.
function readFromFile($lenght, $pos = 0) {
$return = '';
$fp = fopen(FILENAME, 'rb');
if(!$fp) {
// show something
}
$fseek = fseek($fp, $pos, SEEK_SET);
if($fseek == -1) {
// show something
}
$data = fread($fp, $lenght);
$data = unpack("h*", $data);
$arr = str_split(current($data), 2);
foreach($arr as $val) {
$return .= chr(hexdec($val));
}
return $return;
}
Now, you create your string and write to the file:
$data = 'This should work properly, thanks for StackOverFlow!';
$len = strlen($data);
writeToFile($data);
Then read back:
echo readFromFile($len);
The content of your file will look like this:
E<86><96>7^B7<86>öWÆF^Bwö'¶^B^G'ö^GV'Æ<97>Â^BG<86>^Væ¶7^Bfö'^B5G^V6¶ôgV'dÆöw^R