[英]Append html code to file using PHP
我有一个接受字符串并将其通过ajax发送到PHP页面的Javascript函数。 在PHP中,我会将这个字符串放在html文件的head标签(已经存在)中。 此更改应该是最终的。 我该怎么办? 我不知道如何通过PHP处理html代码。
如果您不能使用JS,则只需使用if / else语句,并从ajax向您的标签回显字符串。
解决此问题的一种方法是使用file_get_contents,然后使用修改后的代码对标签进行字符串替换,然后使用修改后的代码编写更改。
例
<?php
$file = "myhtmlfile.html";
$original = file_get_contents($file);
$needle = "<head>";
$new_content = "<head>\n".$_POST['header'];
$replacement = str_replace($needle, $new_content, $original);
file_put_contents($replacement, $file);
?>
<?php
$htmlpage = file_get_contents('http://example.com/index.html');
echo str_replace("<head>", "<head>New text", $htmlpage);
//the result should be from <body></body> to <body>New Text</body>
?>
另外,如果body
标签之间有文本,则可以将其包含在
str_replace("<body>Old Text", "<body>New Text", $htmlpage)
如果您的字符串在变量中,或者您使用的是$_POST
那么请使用"<head>New text"
代替"<head>New text"
"<head>".$_POST['thestring']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.