简体   繁体   中英

Append html code to file using PHP

I have a Javascript function that takes a string and sends it via ajax to a PHP page. In PHP I would put this string inside the head tag (that already exist) of an html file. This change should be final. How could I do this? I don't know how to manipulate html code via PHP.

如果您不能使用JS,则只需使用if / else语句,并从ajax向您的标签回显字符串。

One way around this would be to use file_get_contents, then do a string replace on the tag with the amended code, and then write the changes with the ammended code.

Example

<?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>
?>

Also if you have text between body tags you can include it in

str_replace("<body>Old Text", "<body>New Text", $htmlpage)

If you have the string inside a varibale or you are using $_POST then instead of "<head>New text" put "<head>".$_POST['thestring']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM