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);
Related
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>
Short and clear. I'm not good at regex because I never understood it. But when you look at this simple template, would you say it's possible to replace the %% + the content of it with php brackets + add function brackets to it like this:
Template:
<html>
<head>
<title>%getTitle%</title>
</head>
<body>
<div class='mainStream'>
%getLatestPostsByDate%
</div>
</body>
</html>
It should replace it to this:
<html>
<head>
<title><?php getTitle();?></title>
</head>
<body>
<div class='mainStream'>
<?php getLatestPostsByDate();?>
</div>
</body>
</html>
Is this possible? If yes, how? If anyone got a good tutorial for regEx which explains it even for not so smart guys, I'd be very thankful.
Thanks in advance.
This could be a good start. Get all between your custom tags (%%), and replace it with php code.
https://regex101.com/r/aC2hJ3/1
regex: /%(\w*?)%/g. Check explanation of regex at the right hand side (top), and generated code... it should help.
$template=file_get_contents('template.php');
$re = "/%(\\w*?)%/";
$subst = "<?php $1(); ?>";
$result = preg_replace($re, $subst, $template);
file_put_contents('template.php',$result);
Try this
$html = str_replace ('%getLatestPostsByDate%', '<?php getLatestPostsByDate();?>', $html);
If, however you are looking for a generic solution then you have to use regex
Using the following code:
$tidy = new tidy();
$clean = $tidy->repairString("<p>Hello</p>");
This encases the string in the whole shenanigans:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title></title>
</head>
<body>
<p>Hello</p>
</body>
</html>
Since I'm using it on a "description" field, containing some html tags from time to time, I just want to use it to fix anomalies in the string, forexample unclosed elements, elements that are closed but not opened and so on, not encase it like this as a full html document.
If the string doesnt contain any html at all, it should just return the input. And if it contains html like the example above, it should fix whatever there is to fix, (which is nothing in this example) and not encase it in a full document.
Anyone know how to make HTML Tidy not encase it like this?
I was struggling with the same problem. But found it in the tidy documentation. If you add 'show-body-only' => true it will not show the complete html header and so on.
$tidy = new tidy();
$input = "<p>A paragraph with <b>bold<b> text";
$clean = $tidy->repairString($input,array('show-body-only' => true));
echo $clean;
will show:<p>A paragraph with <b>bold</b> text</p>
I'm currently working on separating HTML & PHP code here's my code which is currently working for me.
code.php
<?php
$data['#text#'] = 'A';
$html = file_get_contents('test.html');
echo $html = str_replace(array_keys($data),array_values($data),$html);
?>
test.html
<html>
<head>
<title>TEST HTML</title>
</head>
<body>
<h1>#text#</h1>
</body>
</html>
OUTPUT: A
it search and change the #text# value to array_value A it works for me.
Now i'm working on a code to search "id" tags on html file. If it's searches the "id" in ".html" file it will put the array_values in the middle of >
EX: <div id="test"> **aray_values here** </div>
test.php
<?php
$data['id="test"'] = 'A';
$html = file_get_contents('test.html');
foreach ($data as $search => $value)
{
if (strpos($html , $search))
{
echo 'FOUND';
echo $value;
}
}
?>
test.html
<html>
<head>
<title>TEST</title>
</head>
<body>
<div id="test" ></div>
</body>
</html>
My problem is I don't know how to put the array_values in the middle of every ></ search in the .html file.
Desired OUTPUT: <div id="test" >A</div>
function callbackInsert($matches)
{
global $data;
return $matches[1].$matches[3].$matches[4].$data[$matches[3]].$matches[6];
}
$data['test'] = 'A';
$html = file_get_contents('test.html');
foreach ($data as $search => $value)
{
preg_replace_callback('#(<([a-zA-Z]+)[^>]*id=")(.*?)("[^>]*>)([^<]*?)(</\\2>)#ism', 'callbackInsert', $html);
}
Warning: code is not tested and could be improved - re global keyword and what items are allowed between > and
Regular expression explanation:
(<([a-zA-Z]+) - any html tag starting including the last letter of the tag
[^>]* - anything that is inside a tag <>
id=")(.*?)(" - the id attribute and its value
[^>]* - anything that is inside a tag <>
>) - the closing tag
([^<]*?) - anything that is not a tag, tested by opening a tag <
(</\\2>) - the closing tag matching the 2nd bracket, ie. the matching opening tag
Use views (.phtml) files to dynamically generate content. This is native for PHP (no 3rd party required).
See this answer: What is phtml, and when should I use a .phtml extension rather than .php?
and this:
https://stackoverflow.com/questions/62617/whats-the-best-way-to-separate-php-code-and-html
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