Writing to a new line in PHP - php

I have read the thread Writing a new line to file in PHP pasted the exact code of there in my own netbeans IDE but didn't work. The pasted code (with some minor changes) was:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$i = 0;
$file = fopen('ids.txt', 'w');
$gemList=array(1,2,3,4,5);
foreach ($gemList as $gem)
{
fwrite($file, $gem."\n");
$i++;
}
fclose($file);
?>
</body>
</html>
I also tried to write in a new line of file using another code. My code goes like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$fh = fopen("testfile.txt", 'w') or die("Failed to create file");
$text = <<<_END
Line 1
Line 2
Line 3
_END;
fwrite($fh, $text) or die("Could not write to file");
fclose($fh);
echo "File 'testfile.txt' written successfully";
?>
</body>
</html>
but the result in the text file is
12345
and what I expect is
1
2
3
4
5
I greatly appreciate any help. Also my Netbeans version is 8.2 and my running OS is Windows 10.

With your current code, check the page source and it is giving you the correct result.
But remember that you are running it on an html page so if you want a new line, use the <br> tag.
foreach ($gemList as $gem)
{
fwrite($file, $gem."<br>");
$i++;
}
fclose($file);
HTML does not take new lines \n into consideration, unless you specifically set the CSS property white-space:pre;

Ibu's answer is correct if you are displaying on a webpage.
For your fwrite() call, be sure the text viewer you are using understands \n as the EOL character. In other words if you are on Windows, and will only work with the resulting file(s) on Windows, a \n\r (new line and carriage return) is what you want to use for your EOL character(s)
Or, leave as-is, and use a text editor that supports "Unix style line endings" - Notepad++ does...

If you are viewing the content of your file in the browser (eg. echoed in PHP) you need to use the nl2br() PHP function to convert newlines to html's <br/>:
<div>
<?= nl2br(file_get_contents("testfile.txt")); ?>
</div>
Alternatively enclose the file content withing a with CSS white-space property set to "pre":
<div style="white-space: pre">
<?= file_get_contents("testfile.txt"); ?>
</div>

Related

how to put text in middle of two words in php

I am editing a HTML file with Php but when i tried to write some text in between the body tag
it should look like:
<body>Hello</body>
but my code is doing this:
<body><hello
php file:
fwrite($myfile, $html);
$page = strpos($html, "body>");
$pagei = (int)$page + (int)"6";
fseek($myfile, $pagei);
fwrite($myfile, "hello");
I am new in php, i searched internet all day but didn't find anything on how to fix this.
str_replace('<body></body>', '<body>Hello</body>', $allText);
or consider adding placeholders:
<html>
<head></head>
<body>
{content}
</body>
</html>
and then:
str_replace('{content}', 'Hello', $allText);

Can i export a specific lines from file to another?

If have a file A.php which for sure have some lines, and i want to export or copy specific lines from A.php to a new file B.php, So the process goes like this (copy lines from x to y in the A.php- Create a new file with name B.php- Past and save B.php).
So if i want to extract lines from 3 to 8 (for example) in the following code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<?php
$fname= basename(__FILE__,'php');
?>
<title><?php echo $fname; ?></title>
</head>
<body>
<p>This is a test Page</p>
</body>
</html>
How can i do this in details if you can?
From the documentation here:
http://php.net/manual/en/function.file.php
This command splits the file into an array of lines:
// substitute a local file for the URL
$lines = file('http://php.net/manual/en/function.file.php');
echo $lines[0];
// <!DOCTYPE html>
echo $lines[56];
// <![endif]-->
After you have the lines you want you can create a new file and save it. There are 100 ways to do this. Here is one:
http://php.net/manual/en/function.file-put-contents.php
file_put_contents('fileInCurrentDirectory.php', $lines[3], FILE_APPEND | LOCK_EX);
file_put_contents('fileInCurrentDirectory.php', $lines[4], FILE_APPEND | LOCK_EX);
file_put_contents('fileInCurrentDirectory.php', $lines[5], FILE_APPEND | LOCK_EX);
You can use file to convert the file into an array of lines, then array_slice to get the lines you want and finally file_put_contents to export to the new file. Like this:
function A2B($a,$b,$from,$to){
$f = file($a,FILE_IGNORE_NEW_LINES);
$n = array_slice($f,($from-1),($to-$from+1));
file_put_contents($b,implode("\n",$n));
}
and call it like
A2B("a.php","b.php",3,6);

How to echo an PHP tag?

I'm trying to echo a PHP tag by doing this:
echo "<?php echo \"test\"; ?>";
The result should be just "test" without quotes, but my code isn't working. What is happening is that nothing is shown on the page, but the source code is "<?php echo "teste"; ?>"
Most of you will want to know why I want to do this. I'm trying to make my own template system; the simplest way is just using file_get_contents and replacing what I want with str_replace and then using echo.
The problem is, that in the template file, I have to have some PHP functions that doesn't work when I echo the page, is there another simple way to do this? Or if you just answer my question will help a lot!
Here is an example of what I am trying to accomplish:
template.tpl:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>[__TITULO__]</title>
</head>
<body >
<p>Nome: [__NOME__] <br />
Email: [__EMAIL__]<br />
<?php
if ($cidade != "") {?>
Cidade: [__CIDADE__]<br />
<?php
}
?>
Telefone: ([__DDD__]) [__TELEFONE__] <br />
Fax:
([__DDDFAX__]) [__FAX__] <br />
Interesse: [__INTERESSE__]<br />
Mensagem:
[__MENSAGEM__] </p>
</body>
</html>
index.php
<?php
$cidade = "Teste";
$file = file_get_contents('template.php');
$file = str_replace("[__TITULO__]","Esse Título é téste!", $file);
$file = str_replace("[__NOME__]","Cárlos", $file);
$file = str_replace("[__EMAIL__]","moura.kadu#gmail.com", $file);
if ($cidade != "") {
$file = str_replace("[__CIDADE__]",$cidade, $file);
}
echo $file;
?>
I can solve all this just not showing the div that has no content. like if i have a template, and in it i have 2 divs:
<div id="content1">[__content1__]</div>
<div id="content2">[__content2__]</div>
if the time that i set the content to replace the template I set the content1 and not set content 2 the div content2 will not show...
Use htmlspecialchars
That will convert the < > to < and >
You are dealing with two sets of source code here that should never be confused - the server code (PHP, which is whatever is in the <?php ?> tags) and the client (or browser) code which includes all HTML tags. The output of the server code is itself code that gets sent to the browser. Here you are in fact successfully echoing a PHP tag, but it is meaningless to the browser, which is why the browser ignores it and doesn't show anything unless you look at the client code that got sent to it.
To implement templates in this style, either they should not have any PHP code, or the resulting string (which you have stored in $file) should itself be executed as though it were PHP, rather than echoing it straight to the client. There are various ways to do this. One is to parse out the PHP tags in the string, echo everything that is not within the PHP tags and run eval() on everything that is.

Get HTML source code of page with PHP

If I have the html file:
<!doctype html>
<html>
<head></head>
<body>
<!-- Begin -->
Important Information
<!-- End -->
</body>
</head>
</html>
How can I use PHP to get the string "Important Information" from the file?
If you already have the parsing sorted, just use file_get_contents(). You can pass it a URL and it will return the content found at the URL, in this case, the html. Or if you have the file locally, you pass it the file path.
In this simple example you can open the file and do fgets() until you find a line with <!-- Begin --> and saving the lines until you find <!-- End -->.
If your HTML is in a variable you can just do:
<?php
$begin = strpos($var, '<!-- Begin -->') + strlen('<!-- Begin -->'); // Can hardcode this with 14 (the length of your 'needle'
$end = strpos($var, '<!-- End -->');
$text = substr($var, $begin, ($end - $begin));
echo $text;
?>
You can see the output here.
You can fetch "HTML" by this
//file_get_html function from third party library
// Create DOM from URL or file
$html = file_get_html('http://www.example.com/');
and any operation on DOM then read following docs:
http://de.php.net/manual/en/book.dom.php

Output text file with line breaks in PHP

I'm trying to open a text file and output its contents with the code below. The text file includes line breaks but when I echo the file its unformatted. How do I fix this?
Thanks.
<html>
<head>
</head>
<body>
$fh = fopen("filename.txt", 'r');
$pageText = fread($fh, 25000);
echo $pageText;
</body>
</html>
To convert the plain text line breaks to html line breaks, try this:
$fh = fopen("filename.txt", 'r');
$pageText = fread($fh, 25000);
echo nl2br($pageText);
Note the nl2br function wrapping the text.
One line of code:
echo nl2br( file_get_contents('file.txt') );
If you just want to show the output of the file within the HTML code formatted the same way it is in the text file you can wrap your echo statement with a pair of pre tags:
echo "<pre>" . $pageText . "</pre>;
Some of the other answers look promising depending on what you are trying todo.
For simple reads like this, I'd do something like this:
$fileContent = file_get_contents("filename.txt");
echo str_replace("\n","<br>",$fileContent);
This will take care of carriage return and output the text. Unless I'm writing to a file, I don't use fopen and related functions.
Hope this helps.
Before the echo, be sure to include
header('Content-Type: text/plain');
Are you outputting to HTML or plain text? If HTML try adding a <br> at the end of each line. e.g.
while (!feof($handle)) {
$buffer = fgets($handle, 4096); // Read a line.
echo "$buffer<br/>";
}
Trying to get line breaks to work reading a .txt file on Apache2 and PHP 5.3.3 with MacOSX 10.6.6 and Camino, the echo nl2br( $text); didn't work right until I printed the file size first too.
BTW it doesn't seem to matter if the .txt file has Linux/MacOSX LF or Windows CRLF line breaks or the text encoding is UTF-8 or Windows Latin1, Camino gets it out OK.
<?php
$filename = "/Users/Shared/Copies/refrain.txt";
$file_ptr = fopen ( $filename, "r" );
$file_size = filesize ( $filename );
$text = fread ( $file_ptr, $file_size );
fclose ( $file_ptr );
echo ( "File size : $file_size bytes<br> <br>" );
echo nl2br ( $text );
?>
You need to wrap your PHP code into <?php <YOU CODE HERE >?>, and save it as .php or .php5 (depends on your apache set up).
Say you have an index.php file hosted by the web server. You want to insert some multi-line text file contents into it. That's how you do it:
<body>
<div>Some multi-line message below:</div>
<div><?= nl2br(file_get_contents('message.txt.asc')); ?></div>
</body>
This <?= ... ?> part is just a shorthand, which instructs the web server, that it needs to be treated as a PHP echo argument.

Categories