Put an HTML tag on top of / body using string (PHP)

1

Hello I'm doing a software to send Emails in PHP. The person has a form and it sends HTML through a link. But here I will put a simple HTML.

$texto = "<!DOCTYPE HTML>
<html lang='pt-br'>
<head>
 <meta charset='UTF-8'>
 <link rel='stylesheet' type='text/css' href='estilo.css'>
 <title></title>
</head>
<body>
<!--conteúdo do BODY -->
<!--Tag a ser inserida -->
</body>
</html>";

What I want is to insert a tag at the end of the body tag before / body .

<table class="dashedBorder" width="100%" cellspacing="0" cellpadding="0" border="0" align="center" style="width: 550">
<tbody>
<tr>
<td valign="middle" align="center" style="FONT-FAMILY: Arial; WHITE-SPACE: normal; FONT-SIZE: 11px">
<font color="#444444">Esse email foi enviado para [email protected] para parar de receber e-mails clique <a href="">aqui</a> </font>
</td>
</tr>
<tr> </tr>
<tr>
</tbody>
</table>

How can I do this in PHP? Taking into account that every $ text file will have a / body within the variable?

    
asked by anonymous 26.05.2015 / 20:22

2 answers

3

Use the str_replace function to replace one part of the text with another in a string. For example, in your case:

$textoAdicional = '<table>...</table>';
$texto = str_replace('</body>', $textoAdicional . '</body>', $texto);

In this way, I am replacing the string $texto with the </body> with <table>...</table></body> with the% variable.

    
26.05.2015 / 20:30
2

Use htmlspecialchars() to print the text:

echo htmlspecialchars($texto);

This function will escape all special HTML characters.

One detail, your PHP code is invalid, because you are opening the string using double quotation marks and in the middle of the text you are closing it, using the double quotes, even if that is not your intention. The correct one would be to use single quotation marks inside the HTML. Example:

$texto = "<!DOCTYPE HTML>
<html lang='pt-br'>
<head>
  <meta charset='UTF-8'>
  <link rel='stylesheet' type='text/css' href='estilo.css'>
  <title></title>
</head>
<body>
<!--conteúdo do BODY -->
<!--Tag a ser inserida -->
</body>
</html>";

For you not to have to worry about the quotes, use Heredoc in creating your strings, see how it looks and feels better:

$texto = <<<EOD
<!DOCTYPE HTML>
<html lang="pt-br">
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="estilo.css">
  <title></title>
</head>
<body>
<!--conteúdo do BODY -->
<!--Tag a ser inserida -->
</body>
</html>
EOD;
    
26.05.2015 / 20:29