PHP - xml_error_string() Function
The XML Parser xml_error_string() function is used to return the XML parser error description for the generated error code. This function takes a single, required parameter, $err_code. It specifies the XML parser error code returned by the xml_get_error_code() method.
Syntax
Below is the syntax of the XML Parser xml_error_string() function −
string xml_error_string ( int $err_code )
Parameters
This function accepts $err_code parameter which is an error code generated from xml_get_error_code() function.
Return Value
The xml_error_string() function returns the XML parser error explanation for the given error code as generated by xml_get_error_code() on success; and on failure, it returns FALSE.
PHP Version
First introduced in core PHP 4, the PHP XML Parser xml_error_string() function continues to function easily in PHP 5, PHP 7, and PHP 8.
Example 1
Here is the basic example of the XML Parser xml_error_string() function to see the working of this function.
<?php // Define error code here $err_code = 9; // Get error description $err_dis = xml_error_string($err_code); // Display the error description echo "Error Code: $err_code\n"; echo "Error Description: $err_dis\n"; ?>
Output
Here is the outcome of the following code −
Error Code: 9 Error Description: Invalid character
Example 2
This application shows how to use xml_error_string() and xml_get_error_code() to provide errors found during XML processing.
<?php
// Create an XML parser
$parser = xml_parser_create();
// Invalid XML string (unclosed tag)
$xmlData = "<root><tag>Sample</root>";
// Attempt to parse the XML
if (!xml_parse($parser, $xmlData, true)) {
// Get the error code from the parser
$err_code = xml_get_error_code($parser);
// Get the error description
$err_dis = xml_error_string($err_code);
echo "Error Code: $err_code\n";
echo "Error Description: $err_dis\n";
}
// Free the parser
xml_parser_free($parser);
?>
Output
This will generate the below output −
Error Code: 76 Error Description: Mismatched tag
Example 3
This program extends the previous example by showing how to display the error along with the line and column where it took place.
<?php
// Create an XML parser
$parser = xml_parser_create();
// Invalid XML string
$xmlData = "<note><to>User</to><from>Admin</from></note>>";
// Parse the XML
if (!xml_parse($parser, $xmlData, true)) {
// Get the error code
$errorCode = xml_get_error_code($parser);
// Get the error description
$errorDescription = xml_error_string($errorCode);
// Get line and column where the error occurred
$errorLine = xml_get_current_line_number($parser);
$errorColumn = xml_get_current_column_number($parser);
echo "Error Code: $errorCode\n";
echo "Error Description: $errorDescription\n";
echo "Error Line: $errorLine, Column: $errorColumn\n";
}
// Free the parser
xml_parser_free($parser);
?>
Output
This will create the below output −
Error Code: 5 Error Description: Invalid document end Error Line: 1, Column: 45