Martin Dimitrov Martin Dimitrov - 2 months ago 18
PHP Question

DOMDocument node with boolean value

What is the correct way to extract a boolean value from an XML node? I have tried with this:

<?php
$xml = "<node><code>false</code></node>";

$dom = new DOMDocument();
$dom->loadXML($xml);

$nodeList = $dom->getElementsByTagName('code');
if ($nodeList->length == 1) {
if($nodeList->item(0)->nodeValue){
echo 'VALID';
} else {
echo 'NOT VALID';
}
}
?>


but I get
VALID
as a result.

Answer

nodeValue is going to return a string, so you need to do a string comparison. For example:

if($nodeList->item(0)->nodeValue != 'false'){
    echo 'VALID';
} else {
    echo 'NOT VALID';
}

You may also consider using filter_var($string, FILTER_VALIDATE_BOOLEAN) to convert the value to boolean (for example it will also convert "1" or "yes" to a boolean), depending on the type of value you'll get in the XML.

Comments