How to write file as it is? - php

I have a string of code like this:
<?php
echo "Hello World";
?>
Now, I want to write that into a php file just the way it is. What I mean is that I want to write this code with new line characters. So the code gets stored in the above fashion. So, how can I do that?
I had tried to use file append and fwrite, but they write the code in one consecutive line and what I want is to have it divided into 3 lines.
On the first line - <?php
On the second line - echo "Hello world";
On the third line - ?>
But I would like to do it by using only one line of code, that would be something like the below one.
$file = 'people.php';
// The new person to add to the file
$person = "John Smith\n";
// Write the contents to the file,
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);

This should work fine using an heredoc:
file_put_contents('people.php', <<<HEREDOC
<?php
echo "Hello World";
?>
HEREDOC
);

<?php
$File = "new.txt"; //your text file
$handle = fopen($File, 'w');
fwrite($handle, '<?php '."\n".' echo "Hello World "; '."\n".'?>');
?>

Your string should be like this
$str = "<?php
echo \"Hello World\";
?>";
then write it to any fileName.php, php while parsing ignores new lines, only semicolons matters.
Edit 1
Since you want to write your string as code, after following above step you will have all your code in a single line more like a compressed code, which will be not human readable, for making it human friendly, you will have to add formatting, a minimal approach for formatting will be to at least add new line chars and tabs for indentation.
for this you will have to do two things, identify chars (a) where you need to add new line feed and those chars (b) where indentation is required. Now before writing to file do some preprocessing add new line chars for char type (a) and at the same time maintain a stack for adding proper number of tabs for indentation.

Try using the following between each line of code to put it on a new line in the php file:
. PHP_EOL .

You can:
<?php
$yourContent = <<<PHP
<?php
echo "Hello world";
echo "This in an example";
$foo = 2;
$bar = 4;
echo "Foo + Bar = ".($foo+$bar);
?>
PHP;
file_put_contents("yourFile.php", $yourContent);
?>

Try following :
<?php
$file = "helloworld.php";
$content = file_get_contents($file);
print_r(htmlspecialchars($content));
?>
Helloworld.php :
<?php
echo "Hello World";
?>
It'll work fine.

It sounds like you need to add a line break to the end of each line. You can use a regular expression search/replace as follows (where $newData already contains the string you want to append to the file):
<?php
$newData = preg_replace('/$/',"\n", $newData);
file_put_contents($file, $newData, FILE_APPEND | LOCK_EX);
?>
This finds the end of each line (indicated by $ in regex) and adds the new line (\n) at that position.

this code is working on my pc. you will also like it.
<?php
$file = 'people.php';
// The new person to add to the file
$person = "<?php
echo 'Hello World';
?>\n";
// Write the contents to the file,
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
echo $person;
?>

Related

Why does it add the text at the beginning of next line, and not the end of the right one?

Needed solution:
I am working with a simple PHP script that should:
Add "value4:::" at the end of the first line in a file
Add ":::" at the end of all the next lines
I am novise in programming, and have sit here for two days trying to figure this out. Might be a little detail, or it might be totally wrong way of doing this task.
It might be wrong way to do this, or may be a regex problem? I really don't know.
I kindly ask you to help me with the solution.
Information:
The file newstest.db looks like this:
ID:::value1:::value2:::value3:::
1:::My:::first:::line:::
2:::My:::second:::line:::
3:::Your:::third:::line:::
And using this php script I'd like to make it look like this:
ID:::value1:::value2:::value3:::value4:::
1:::My:::first:::line::::::
2:::My:::second:::line::::::
3:::Your:::third:::line::::::
Problem:
So far I have almost got it, but I am confused to why it adds the "value4:::" to the beginning of the second line, and then add ":::" at the beginning (not end) of all of the rest of the lines.
So I get a file that looks like this:
ID:::value1:::value2:::value3:::
value4:::1:::My:::first:::line:::
:::2:::My:::second:::line:::
:::3:::Your:::third:::line:::
I thought that:
$lineshere = 'Some text here:::';
$lines1 = $linehere.'value4:::';
would output "Some text here:::value4:::"
May be the problem is due to this way of adding line after line?
$lines = '';
$lines.= 'My test';
$lines.= ' is here';
echo $lines;
I am a novise in programming, so I might have used totally wrong functions tec to make this work.
But in this case it seams to add a space or line break/ line end in the wrong place.
My try on this solution:
<?php
// specify the file
$file_source="newstest.db";
// get the content of the file
$newscontent = file($file_source, true);
//set a start value (clear memory)
$lines ='';
// get each line and treat it line by line.
foreach ($newscontent as $line_num => $linehere) {
// add "value4:::" at the end of FIRST line only, and put it in memory $lines
if($line_num==0) {
$lines.= $linehere.'value4:::';
// Just to see what the line looks like
//echo 'First line: '.$lines.'<br /><br />';
}
// then add ":::" to the other lines and add them to memory $lines
if($line_num>0) {
$lines1 = $linehere.':::';
$lines.= $lines1;
//just look at the line
//echo 'Line #'.$line_num.': '.$lines1.'<br /><br />';
}
}
//Write new content to $file_source
$f = fopen($file_source, 'w');
fwrite($f,$lines);
fclose($f);
echo "// to show the results ar array<br /><br />";
$newscontentlook = file($file_source, true);
print_r(array_values($newscontentlook));
?>
This is actually very easy to achieve with file_get_contents and preg_replace, i.e:
$content = file_get_contents("newstest.db");
$content = preg_replace('/(^ID:.*\S)/im', '$1value4:::', $content);
$content = preg_replace('/(^\d+.*\S)/im', '$1:::', $content);
file_put_contents("newstest.db", $content);
Output:
ID:::value1:::value2:::value3:::value4:::
1:::My:::first:::line::::::
2:::My:::second:::line::::::
3:::Your:::third:::line::::::
Ideone Demo
the function file() gives you the file in an array with each line being an element of the array. Each ending of the line (EOL) is included in the elements. So appending text to that line will be after the EOL, and thus effectively on the beginning of the next line.
You can either choose to not use file() and explode the text yourself on the EOL, so the EOL is no longer part of the array element. Then edit the elements, and implode the array again.
Or fopen() the file, and fread() through it yourself. The latter option is preferred, as it won't load the entire file into memory at once.
I think the problem is in your loop through the lines read by file() function:
foreach ($newscontent as $line_num => $linehere) {
...
$linehere contains a newline at the end, so you should simply chop it before using it:
foreach ($newscontent as $line_num => $linehere) {
$linehere = chop($linehere);
...
If you don't chop the line contents, when you concatenate a string to it, you'll get:
LINE_CONTENTS\nSTRING_ADDED
which, when printed, will be:
LINE_CONTENTS
STRING_ADDED
Hope this helps...

Php putting amount of characters after string

I'm a front end developer but I'm learning php so I can do basic back end stuff. My code seems to be putting the amount of characters after the echoed string.
<?php
$openFile = fopen("file.txt","w");
$name = "Chris";
fwrite($openFile,$name);
fclose($openFile);
$openFile = fopen("file.txt","r");
echo readfile("file.txt");
fclose($openFile);
?>
This is what I get for posting here. -2.
Live preview: http://icodewebsitesandineedatestingserver.netai.net/
I guess you're trying to read the contents of the file?
PHP doc on readfile:
Reads a file and writes it to the output buffer.
5 is the number of bytes read.
You can use file_get_contents:
<?php
$openFile = fopen("file.txt","w");
$name = "Chris";
fwrite($openFile,$name);
fclose($openFile);
echo file_get_contents("file.txt");
?>

Read text file and print in the same format

i want to read a text file on a php page and print (echo) the content in the same form (with the paragraphs). So i tried two implementations
Code 1
$textfile = "teste.txt"; // Declares the name and location of the .txt file
$content="";
$fileLocation = "$textfile";
$fh = fopen($fileLocation, 'w ');
if (is_readable($textfile)) {
$content .= fread($fh, 8192);
echo $content;
} else {
echo 'The file is not readable.';
}
fclose($fh);
?>
Using this code nothing apper on the screen. and i had another problem. If i used filesize ($textfile) on the fread i had this error Length parameter must be greater than 0.So i guess this is the problem. but the text file has content
Code 2
<?php
$homepage = file_get_contents('teste.txt');
echo $homepage;
?>
This code works. but the format is not what i want.
the echo prints this
25 ºC 26 ºC 27 ºC 26 ºC 26 ºC
I want that appear one value on each line like i have on the text file.
What can i do to acomplish that
Thanks for the help
note sure if this is answerd, but try this
<?php
$file = "LOCATION/NAME.txt";
$text = file_get_contents($file);
$text = nl2br($text);
echo $text;
?>
This should be as simple as wrapping the output inside the PRE tag:
<?php
$homepage = file_get_contents('teste.txt');
echo '<PRE>' . $homepage . '</PRE>';
?>
This will work better than nl2br() if you also need to keep the exact number of spaces due to needing a fixed-width font. HTML normally turns two or three spaces in a row into just one. But inside a PRE tag if you have 3 spaces, all 3 will be displayed.

I am using fgets() to read in a line in PHP. But i am getting a wierd result?

$size = intval(trim(fgets($fp,4)));
$triangle = range(1,$size);
for($j=0;$j<$size;$j=$j+1)
$triangle[$j] = split(" ",trim(fgets($fp,400)));
This code reads in the number of lines to read, then reads them one by one. Issue is, when first input line ends in space, it reads that space as a new line.
you can read full file content by file_get_contents.
<?php
$content= file_get_contents('myfile.txt');
echo $content;
?>

In PHP when using fgets() to read from file how to exclude "brake row"

I'm writing simple function witch will read data from myfile.txt with fgets().
Content of file is something like:
1
2
3
4
Function to get first value (1):
$f = fopen ("myfile.txt", "r");
$mystring = fgets ($f);
Now, when I use $mystring to write in file like:
$f1 = fopen ("myfile2.txt", "w");
fwrite($f1, 'text' . $mystrin . 'more text');
text 'more text' goes to new row.
I want to have it in in same row with other text.
When reading a file using fgets() it will include the newline at the end. You only need to remove it.
$mystring = trim ($mystring);
This will remove any leading and trailing whitespaces.
$mystring = rtrim ($mystring, PHP_EOL);
Will remove any trailing newlines.

Categories