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:

<?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";
}

Watch a course Learn object oriented PHP

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.

<?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 the above examples will check if the string is a valid XML and will not display any warnings.