LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   PHP function to check if string is valid xml? (https://www.linuxquestions.org/questions/programming-9/php-function-to-check-if-string-is-valid-xml-650290/)

j-ray 06-19-2008 07:00 AM

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

sxeraverx 06-19-2008 07:08 AM

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.

rubadub 06-19-2008 07:09 AM

Not off the top of my head, also can't think how you'd do it with regex either. Yet you can use this to find out what was wrong with it and act accordingly.

You could start looking here though...

j-ray 06-19-2008 07:49 AM

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 ;-)

rubadub 06-19-2008 08:03 AM

@ supresses errors!


Use a try/catch clause, here's an example for mysql...
Code:

try
        {
                if ( !@ ( $conn = mysql_connect($db_host, $db_uname, $db_pass) ) )
                        throw new Exception (mysql_error());
        }
        catch (Exception $e)
        {
                //echo 'ERROR: ' . $e->getMessage();
                return array(-1, $conn, "?");
        }


ctrahey 06-29-2009 02:34 PM

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

neelkamalpandey 12-19-2009 07:46 AM

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.