How to display XML in HTML in PHP?

To display XML content within HTML pages using PHP, you need to escape special characters to prevent browser interpretation. The most effective method is using the htmlentities() function combined with HTML <pre> tags to preserve formatting.

Basic Method

The simplest approach uses htmlentities() to convert XML tags into HTML entities ?

<?php
$xmlString = "<root><item>Sample Data</item></root>";
echo '<pre>' . htmlentities($xmlString) . '</pre>';
?>
<root><item>Sample Data</item></root>

Complete Example

Here's a more detailed example showing how to display formatted XML content ?

<?php
$xmlString = "
<example>
    <item>
        <name>Product Name</name>
        <price>29.99</price>
    </item>
</example>";

echo '<pre>' . htmlentities($xmlString) . '</pre>';
?>
<example>
    <item>
        <name>Product Name</name>
        <price>29.99</price>
    </item>
</example>

Alternative Method

You can also use htmlspecialchars() for basic escaping ?

<?php
$xml = "<user><name>John & Jane</name></user>";
echo '<pre>' . htmlspecialchars($xml) . '</pre>';
?>
<user><name>John & Jane</name></user>

Key Points

  • htmlentities() − Converts all applicable characters to HTML entities
  • htmlspecialchars() − Converts only special characters (<, >, &, quotes)
  • <pre> tags − Preserve whitespace and formatting

Conclusion

Use htmlentities() with <pre> tags to safely display XML content in HTML. This method preserves formatting while preventing browser interpretation of XML tags.

Updated on: 2026-03-15T08:48:57+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements