PHP function to check if string is valid xml?
Hi,
we are using simplexml_load_string() function that expects a valid xml string as first argument to generate some output with php. Unfortunately not every input gathered and sent to the function is valid xml. Sometimes html or text. Is there a way to check whether a given string is valid xml in php? The files are not very big in general. Do you have an idea how to accompish that? Would be great if you let me know, thanks! j |
simplexml_load_string will return false if it's not a valid XML string. Go ahead and load it, and then just check the return value:
$a = simplexml_load_string($somestring); if($a===FALSE) { //It was not an XML string } else { //It was a valid XML string } Make sure to use ===, as some functions can return values that evaluate to false (like null, or an empty array, or an empty string), but you need to check for specifically false. |
|
as you said simplexml_load_string will return false if the string is not valid xml but unfortunately it spits out a lot of warnings that we want to avoid. But thanks anyway! I had not noticed it was like that before ;-)
|
@ supresses errors!
Use a try/catch clause, here's an example for mysql... Code:
try |
You can supress
Without digging up a more robust solution, you can combine error suppression and the false check:
@$a = simplexml_load_string($somestring); ... check $a |
Thanks for the help
Thanks for the help i was trying to validate my xml query string that is passed for one of my api and this was useful there.
Could you provide me some examples on could i validate GMT in php. |
All times are GMT -5. The time now is 08:43 PM. |