I'm writing a script in PHP to change some codes in HTML files. Every file will be read in line per line and thus every operation has to be per line. My problem is that some operations lose the newline character if it is the end of the file.
Just to be clear, I don't want to have HTML newline characters (<br />
) but I want normal newline characters (\n
) to get a better formatted code inside the code editor.
HTML example before:
<body>
<div id="wrapper">
HTML example after:
<body>
<div id="jobtempl"> <!-- jobtempl --><div id="wrapper">
How it should be:
<body>
<div id="jobtempl"> <!-- jobtempl -->
<div id="wrapper">
PHP Code:
private function replaceContent($file) {
$this->file = $file;
$lines = file($this->file);
// some stuff to get $bodyStartLine as line number where to add the code
$handle = fopen($this->file, 'w');
foreach ($lines as $line) {
if ($i == $bodyStartLine) {
$line = $line . '<div id="jobtempl"> <!-- jobtempl -->';
}
if ($i == $bodyEndLine) {
$line = '</div> <!-- /jobtempl -->' . PHP_EOL . $line; // works
}
fwrite($handle, $line);
}
fclose($handle);
}
Even if I use $line = $line . '<div id="jobtempl"> <!-- jobtempl -->' . "\n";
to force a newline character it doesn't work. The same with \r\n\
and \r
.
What works is when I later close this new div:
$line = '</div> <!-- /jobtempl -->' . "\n" . $line;
So whenever there is something after the newline character to add, it will work. Is it possible to get it working without adding new content after the newline character?