Page Title

5 Methods to Display HTML Content as Text in PHP: Tips and Examples

Learn how to display HTML tags as plain text and print clean HTML code in PHP with these 5 methods. Get helpful tips and code examples to improve your PHP development skills today.

  • Using htmlspecialchars() Function
  • Surrounding Output with xmp Tags
  • How to use HTML Tags inside PHP echo Statement
  • Printing Clean HTML Code Using Link Rel Tag
  • Using html2text Library
  • Rendering HTML at Runtime
  • Other simple code examples for displaying HTML content as text in PHP
  • Conclusion
  • How to print HTML as text in PHP?
  • How do I display HTML code as text?
  • Can PHP render HTML?
  • How to display PHP code in HTML?
Читайте также:  Python manual на русском

PHP is a popular programming language used for web development. One common task in PHP is displaying html tags as plain text and printing HTML content. In this article, we’ll provide various methods to achieve this, as well as important points and helpful tips for php development.

Using htmlspecialchars() Function

The htmlspecialchars() function is used to convert special characters to HTML entities. This function can be used to display html tags as plain text. Here’s an example:

$html = "

Hello World!

";
echo htmlspecialchars($html); // Output:

Hello World!

As you can see, the htmlspecialchars() function converts the HTML tags to their corresponding HTML entities, which are then displayed as plain text.

Surrounding Output with xmp Tags

Another method to display HTML tags as plain text is to surround the output with xmp tags. This method is simple and effective. Here’s an example:

$html = "

Hello World!

";
echo "$html"; // Output:

Hello World!

As you can see, the xmp tags surround the HTML code and display it as plain text.

How to use HTML Tags inside PHP echo Statement

The link rel tag can be used to print clean HTML code in front. This method is useful for printing HTML content in PHP. Here’s an example:

$html = "

Hello World!

";
echo " "; // Output:

Hello World!

As you can see, the link rel tag is used to print clean HTML code in front of the actual content.

Using html2text Library

The html2text library can be used to convert HTML to plain text for email purposes. This method is useful for displaying HTML content in emails. Here’s an example:

require_once 'vendor/autoload.php'; use voku\helper\HtmlDomParser;$html = "

Hello World!

";
$dom = HtmlDomParser::str_get_html($html); echo $dom->text(); // Output: Hello World!

As you can see, the html2text library is used to convert the HTML to plain text.

Rendering HTML at Runtime

PHP can render HTML at runtime, such as through the use of echo statements or the creation of links within PHP methods. This method is useful for displaying dynamic content. Here’s an example:

$html = "

Hello World!

";
echo $html; // Output:

Hello World!

As you can see, the echo statement is used to render the HTML at runtime.

Other simple code examples for displaying HTML content as text in PHP

In Php , for example, php echo html as text code example

echo '
'; echo htmlspecialchars($YOUR_HTML); echo '

';

In Php , for example, how to use php to print inside html

In Php case in point, php print html code code sample

Conclusion

Displaying HTML tags as plain text and printing HTML content are common tasks in php. We have provided various methods to achieve this, including using the htmlspecialchars() function, surrounding output with xmp tags, printing clean HTML code using link rel tag, using html2text library, and rendering HTML at runtime.

In addition, we have discussed some helpful tips for PHP development. It is important to sanitize user input to prevent security vulnerabilities, and to use proper indentation and commenting practices to ensure code readability.

By following these best practices and utilizing the methods outlined in this article, you can effectively display HTML tags as plain text and print HTML content in PHP.

Frequently Asked Questions — FAQs

What is the htmlspecialchars() function and how does it display HTML tags as plain text in PHP?

The htmlspecialchars() function converts special characters to HTML entities, which can be used to display HTML tags as plain text in PHP. Simply pass the HTML code as a string argument to the function and it will convert the special characters accordingly.

Can I use the xmp tags to display HTML content as plain text in PHP?

Yes, the xmp tags can be used to surround HTML content and display it as plain text in PHP. This method is simple and effective, and a code example is provided in this article to demonstrate how to use it.

The link rel tag can be used to print clean HTML code in front, which is useful for printing HTML content in PHP. This tag specifies the relationship between the current document and the linked document, and can be used to provide a clean version of the HTML code for printing purposes.

What is the html2text library and how does it convert HTML to plain text in PHP?

The html2text library is a PHP library that converts HTML to plain text for email purposes. This method is useful for displaying HTML content in emails, and a code example is provided in this article to demonstrate how to use it.

Can PHP render HTML at runtime and display dynamic content?

Yes, PHP can render HTML at runtime through the use of echo statements or the creation of links within PHP methods. This method is useful for displaying dynamic content, and a code example is provided in this article to demonstrate how to use it.

What are some best practices for displaying HTML content as text in PHP?

Some best practices include using proper HTML syntax, ensuring the HTML code is valid, and using the appropriate method for the task at hand. It’s also important to sanitize user input to prevent security vulnerabilities.

Источник

DOMDocument::saveHTML

Creates an HTML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

Parameters

Optional parameter to output a subset of the document.

Return Values

Returns the HTML, or false if an error occurred.

Examples

Example #1 Saving a HTML tree into a string

$root = $doc -> createElement ( ‘html’ );
$root = $doc -> appendChild ( $root );

$head = $doc -> createElement ( ‘head’ );
$head = $root -> appendChild ( $head );

$title = $doc -> createElement ( ‘title’ );
$title = $head -> appendChild ( $title );

$text = $doc -> createTextNode ( ‘This is the title’ );
$text = $title -> appendChild ( $text );

See Also

  • DOMDocument::saveHTMLFile() — Dumps the internal document into a file using HTML formatting
  • DOMDocument::loadHTML() — Load HTML from a string
  • DOMDocument::loadHTMLFile() — Load HTML from a file

User Contributed Notes 18 notes

As of PHP 5.4 and Libxml 2.6, there is currently simpler approach:

when you load html as this

$html->loadHTML($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

in the output, there will be no doctype, html or body tags

When saving HTML fragment initiated with LIBXML_HTML_NOIMPLIED option, it will end up being «broken» as libxml requires root element. libxml will attempt to fix the fragment by adding closing tag at the end of string based on the first opened tag it encounters in the fragment.

Foo

bar

Foo

bar

Easiest workaround is adding root tag yourself and stripping it later:

$html->loadHTML(‘‘ . $content .’‘, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$content = str_replace(array(‘‘,’‘) , » , $html->saveHTML());

This method, as of 5.2.6, will automatically add and tags to the document if they are missing, without asking whether you want them. In my application, I needed to use the DOM methods to manipulate just a fragment of html, so these tags were rather unhelpful.

Here’s a simple hack to remove them in case, like me, all you wanted to do was perform a few operations on an HTML fragment.

I am using this solution to prevent tags and the doctype from being added to the HTML string automatically:

$html = ‘

Hello world!

‘ ;
$html = ‘

‘ . $html . ‘

‘ ;
$doc = new DOMDocument ;
$doc -> loadHTML ( $html );
echo substr ( $doc -> saveXML ( $doc -> getElementsByTagName ( ‘div’ )-> item ( 0 )), 5 , — 6 )

// Outputs: «

Hello world!

»
?>

Since PHP/5.3.6, DOMDocument->saveHTML() accepts an optional DOMNode parameter similarly to DOMDocument->saveXML():

If you load HTML from a string ensure the charset is set.

Otherwise the charset will be ISO-8859-1!

Tested in PHP 5.2.9-2 and PHP 5.2.17.
saveHTML() игнорирует свойство DOMDocument->encoding. Метод saveHTML() сохраняет html-документ в кодировке, которая указана в теге исходного (загруженного) html-документа.
saveHTML() ignores property DOMDocument->encoding. Method saveHTML() saves the html-document encoding, which is specified in the tag source (downloaded) html-document.
Example:
file.html. Кодировка файла должна совпадать с указанной в теге . The encoding of the file must match the specified tag .


Русский язык

error_reporting (- 1 );
$document =new domDocument ( ‘1.0’ , ‘UTF-8’ );
$document -> preserveWhiteSpace = false ;
$document -> loadHTMLFile ( ‘file.html’ );
$document -> formatOutput = true ;
$document -> encoding = ‘UTF-8’ ;
$htm = $document -> saveHTML ();
echo «Записано байт. Recorded bytes: » . file_put_contents ( ‘file_new.html’ , $htm );
?>
file_new.html будет в кодировке Windows-1251 (НЕ в UTF-8).
file_new.html will be encoded in Windows-1251 (not in UTF-8).

saveHTML() и file_put_contents() позволяют преодолеть недостаток метода saveHTMLFile().
Смотрите мой комментарий к методу saveHTMLFile().
saveHTML() and file_put_contents() allows you to overcome the lack of a method saveHTMLFile().
See my comment on the method saveHTMLFile().
http://php.net/manual/ru/domdocument.savehtmlfile.php

To solve the script tag problem just add an empty text node to the script node and DOMDocument will render nicely.

To avoid script tags from being output as

$doc = new DOMDocument ();
$doc -> loadXML ( $xmlstring );
$fragment = $doc -> createDocumentFragment ();
/* Append the script element to the fragment using raw XML strings (will be preserved in their raw form) and if succesful proceed to insert it in the DOM tree */
if( $fragment -> appendXML ( «» ) <
$xpath = new DOMXpath ( $doc );
$resultlist = $xpath -> query ( «//*[local-name() = ‘html’]/*[local-name() = ‘head’]» ); /* namespace-safe method to find all head elements which are childs of the html element, should only return 1 match */
foreach( $resultlist as $headnode ) // insert the script tag
$headnode -> appendChild ( $fragment );
>
$doc -> saveXML (); /* and our script tags will still be */

If you want a simpler way to get around the

$script = $doc -> createElement ( ‘script’ );\
// Creating an empty text node forces
$script -> appendChild ( $doc -> createTextNode ( » ));
$head -> appendChild ( $script );

If created your DOMDocument object using loadHTML() (where the source is from another site) and want to pass your changes back to the browser you should make sure the HTTP Content-Type header matches your meta content-type tags value because modern browsers seem to ignore the meta tag and trust just the HTTP header. For example if you’re reading an ISO-8859-1 document and your web server is claiming UTF-8 you need to correct it using the header() function.

header ( ‘Content-Type: text/html; charset=iso-8859-1’ );
?>

Источник

Оцените статью