Skip to content

How check if a String is a Valid XML with-out Displaying a Warning in PHP

In PHP, you can use the simplexml_load_string function to check if a string is a valid XML without displaying a warning. This function returns an object of the SimpleXMLElement class on success, and FALSE on failure. Here's an example of how to use it:

Example of using the simplexml_load_string function to check if a string is a valid XML without displaying a warning in PHP

php
<?php

$xml_string = "<root><element>text</element></root>";
$xml = @simplexml_load_string($xml_string);
if ($xml === false) {
  // Invalid XML
  print "Invalid XML";
} else {
  // Valid XML
  print "Valid XML";
}

<div class="alert alert-info flex not-prose"> Watch a course Learn object oriented PHP</div>

Alternatively, you can use libxml_use_internal_errors(true) to disable libxml errors and then you can use libxml_get_errors() function to check for errors.

Example of using libxml_use_internal_errors(true) to disable libxml errors and then libxml_get_errors() function to check for errors in PHP

php
<?php

libxml_use_internal_errors(true);
$xml_string = "<root><element>text</element></root>";
$xml = simplexml_load_string($xml_string);
$errors = libxml_get_errors();
if (empty($errors)) {
  //valid xml
  print "Valid XML";
} else {
  //Invalid xml
  print "Invalid XML";
}
libxml_clear_errors();
libxml_use_internal_errors(false);

Both examples check if the string is valid XML without displaying warnings. The first method uses the @ error suppression operator for simplicity. The second method uses libxml_use_internal_errors() and libxml_get_errors(), which is preferable when you need to capture and inspect detailed error messages for debugging or logging.

Dual-run preview — compare with live Symfony routes.