The esc_xml() WordPress PHP function is used to escape text for XML blocks.
Usage
Let’s say you have a string which needs to be included in an XML structure. The function will help you escape it properly.
$text = "I love <WordPress & PHP!"; $escaped_text = esc_xml($text); echo $escaped_text;
In this example, the output would be: I love <WordPress & PHP!
Parameters
- $text (string): The text that you want to escape.
More information
See WordPress Developer Resources: esc_xml()
This function is part of the WordPress core, and it’s used for safe rendering of XML content.
Examples
Escaping a Simple String
In this example, we escape a simple string with some special characters that need to be escaped in XML:
$text = "Hello <world>!"; $escaped_text = esc_xml($text); echo $escaped_text; // Output: Hello <world>!
Escaping a String with HTML Entities
Here, we’ll escape a string that contains HTML entities:
$text = "3 > 2 and 2 < 3"; $escaped_text = esc_xml($text); echo $escaped_text; // Output: 3 > 2 and 2 < 3
Escaping a String with Ampersands
This example escapes a string that contains ampersands:
$text = "Fish & Chips"; $escaped_text = esc_xml($text); echo $escaped_text; // Output: Fish & Chips
Escaping a String with Quotes
We can also escape a string that contains quotes:
$text = '"Hello", said the man.'; $escaped_text = esc_xml($text); echo $escaped_text; // Output: "Hello", said the man.
Escaping a Complex String
Finally, we’ll escape a more complex string with a variety of characters that need to be escaped:
$text = '<a href="http://example.com">Link</a> & "Quoted Text"'; $escaped_text = esc_xml($text); echo $escaped_text; // Output: <a href="http://example.com">Link</a> & "Quoted Text"