Why PHP isn't display the last line of a file? - php

I would like to display the last line of an XML file, to see if it has a valid closing tag (e.g. )
But my code doesn't diplay this last line.
$xml_input = file('whatever.xml');
$last line = trim(implode("", array_slice($xml_input, -1)));
echo "Last line is : " . $last_line;
The file exist at the same location where the PHP file is, and file_get_contents can read it (so no problem with access rights), and can display it using echo.
(Although it is strange that file_get_contents removes the xml tags, and displays only the information inside the tagged areas.)
Could you help me what the problem is with my code?

You can use fopen() and fread() to read the xml file like:
<?php
$myfile = fopen("whatever.xml", "r") or die("Unable to open file!");
// read untill the endand print that
echo fread($myfile,filesize("whatever.xml"));
// you can save it in a variable and do string handling work.
fclose($myfile);
?>

Related

How can i save all the variable results from a echo into a txt file using php?

I wrote a php script that generates random tokens, and I want to output these tokens into a .txt file.
Below is the code:
do {
$token = bin2hex(random_bytes(2));
echo("token: $token");
$myfile = fopen("output.txt", "w+") or die("Unable to open file!");
fwrite($myfile, $token);
fclose($myfile);
} while ($token != "e3b0");
It echos multiple tokens, until the echo = e3b0, but when I try to write the result on a txt file, it only writes "e3b0", is that a way to write all the results of the "echo" into a txt file?
As I see it the most efficient way to do this would be to do everything just enough times.
Meaning we have to loop and generate the codes, but we only need to write to the file once,same thing with the echo.
$code = "start value";
while ($code != "e3b0"){
$arr[] = $code = bin2hex(random_bytes(2));
}
echo $str = implode("\n", $arr);
file_put_contents("output.txt", $str);
This is do everything just enough times, and a more optimized code.
But if you run this in a browser then it will not output them on separate lines on screen, only in the txt file. But if you open the source it will be on separate lines.
That is because I did not use the br tag in the implode.
EDIT: Efficiency was never asked in original OP question. This post is being edited to include efficiency, namely no need to reopen and close a file.
Your use of w+ will always place the file pointer at the beginning of the file and truncate the file in the process. So as a result, you always end up with the last value written.
From php.net on fopen w+:
Open for reading and writing; place the file pointer at the beginning of the file
and truncate the file to zero length. If the file does not exist, attempt to create it.
Using your existing code, a solution then would be as follows:
$myfile = fopen("output.txt", "a+") or die("Unable to open file!");
do {
$token = bin2hex(random_bytes(2));
echo("token: $token");
fwrite($myfile, $token);
} while ($token != "e3b0");
fclose($myfile);
Where a+ in the same docs says:
Open for reading and writing; place the file pointer at the end of the file.
If the file does not exist, attempt to create it. In this mode, fseek()
only affects the reading position, writes are always appended.
Source:
https://www.php.net/manual/en/function.fopen.php
Amendments:
As #andreas mentions, opening and closing the file repeatedly inside the loop is not necessary (nor efficient). Since you are appending, you can open it once with a+ before the loop begins; and close it after the loop ends.
In terms of having a separator char between tokens written to the file, a carriage return (line break) is a good choice. In this way you can reduce the amount of parsing you would have to program when programmatically reading the file. For this, your writes could be written as follows:
fwrite($myfile, $token . "\n");

Why does it remove the content of the file?

I've been getting irritated by this bug, and I've tried to fix it but it's been a struggle for me. So I have a php file write to a .txt file, but as I enter different info, it replaces the info that was already in the file, but I don't want it to do that. I want it to add on. Help?
<?php
$filenum = echo rand();
$info = $_GET["info"]; //You have to get the form data
$file = fopen('$filenum.txt', 'w+'); //Open your .txt file
$content = $info. PHP_EOL .$gain. PHP_EOL .$offset;
fwrite($file , $content); //Now lets write it in there
fclose($file ); //Finally close our .txt
die(header("Location: ".$_SERVER["HTTP_REFERER"]));
?>
You're using w+ mode, and the documentation clearly says:
Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
If you want to append, you should use a or a+.
BTW, I'm not nor sure why you're using w+ rather than just w, since you're never reading the file.
Also, you can do it all in one statement using file_put_contents()
$filenum = rand();
$info = $_GET['info'];
$content = $info . PHP_EOL . $gain . PHP_EOL . $offset . PHP_EOL;
file_put_contents("$filenum.txt", $content, FILE_APPEND);
die(header("Location: " . $_SERVER['HTTP_REFERER']));
And notice that you should have PHP_EOL at the end of $content. Otherwise, every time you add to the file, it will start on the same line as the last line you added previously.
I don't know the solution but I would recommend you to see the file format you are opening in, I think it should be 'a+' or something like that which opens file for appending rather than 'w+'. I haven't used php much but I think that's the case

Can't add line break while storing string to a txt file in PHP

Simple code to learn how to open, write to a txt file and read it. I am having two issues.
I can't seem to add an actual line break while storing string in .txt file.
Echo is NOT printing the text in the browser
Code
<html>
<body>
<?php
$myfile=fopen("testfile.txt", "a") or die("unable to open file");
$txt=("john doe<br>");
fwrite($myfile, $txt);
$txt=("jane doe<br>");
fwrite($myfile,$txt);
echo fread($myfile, filesize("testfile.txt"));
?>
</body>
</html>
contents of .txt file ( as you can see it is literally adding line break tag in the txt file instead of adding a break)
john doe<br>jane doe<br>
Also please suggest why the echo is not printing when I run the PHP file in Chrome.
For the first part
The proper code would be
<html>
<body>
<?php
$myfile=fopen("testfile.txt", "a") or die("unable to open file");
$txt=("john doe\n");
fwrite($myfile, $txt);
$txt=("jane doe\n");
fwrite($myfile,$txt);
echo fread($myfile, filesize("testfile.txt"));
?>
</body>
</html>
<br> is a html tag and is rendered only in browser, for files you should use carriage return which is \n
As far as second question goes, i think that you are trying to open the .php file directly in browser, That is not the proper way to do that. Browser can only run js files. The php files run on your server, (usually apache/nginx). You can find a lot of manuals on how to configure them with php and the view the rendered output in browser.
For line break you are using <br> tag, it's line break for HTML. To write new line in file you can use PHP_EOL. It's PHP constant that adds \n for UNIX alike system and \r\n for windows, resulting line break in the file.
// Concat new line to string
$txt = "john doe".PHP_EOL;
fwrite($myfile, $txt);
// Concat new line to string
$txt = "jane doe".PHP_EOL;
fwrite($myfile, $txt);

How to add additional text to file php

This is my code:
$open = fopen('emails.txt', 'w+');
if ($open) {
$content = "$first $last <$email>,";
if (fwrite($open, $content)) {
// ...
}
}
However, when I run this, it just replaces the text I already have in the file. How do I just add to the file, instead of replacing it?
You have to open the file in append mode, by passing a as the second parameter to fopen():
$open = fopen("emails.txt", 'a');
Then, data you write to the file will be appended to the end of the file, preserving data that was previously written to the file.
If you're only appending one block of text into the file at every request, you could look into file_put_contents() as well:
file_put_contents('emails.txt', $content, FILE_APPEND);
Shorter than having to write fopen(), fwrite() and fclose(), though the latter is more or less optional :)

Problems with replacing text in a text file

I have the following scenarion.
Everytime my page loads I create a file. Now my file has two tags within. {theme}{/theme} and {layout}{/layout}, now everytime I choose a certain layout or theme it should replace the tags with {layout}layout{/layout} and {theme}theme{/theme}
My issue is that after I run the following code
if(!file_exists($_SESSION['file'])){
$fh = fopen($_SESSION['file'],"w");
fwrite($fh,"{theme}{/theme}\n");
fwrite($fh,"{layout}{/layout}");
fclose($fh);
}
$handle = fopen($_SESSION['file'],'r+');
if ($_REQUEST[theme]) {
$theme = ($_REQUEST[theme]);
//Replacing the theme bracket in the cache file for rememberence
while($line=fgets($handle)){
$line = preg_replace("/{theme}.*{\/theme}/","{theme}".$theme."{/theme}",$line);
fwrite($handle, $line);
}
}
My output looks as follows
{theme}{/theme}
{theme}green{/theme}
And it needs to look like this
{theme}green{/theme}
{layout}layout1{/layout}
I rarely use random-access file operation but like to read it all as text and write ti back so I might be wrong here. BUT as I can see, you read the first line (so the pointer is at the beginning of the second line). Then you write '{theme}green{/theme}' into that file so it replaces the next position text (the second line).
In this case (as your data is small), you better get the hold file. Change it as string and write it back.

Categories