0

I am a newcomer to PHP and SimpleXMl.

I would not expect false under either of these tests.

  $xml=new SimpleXMLElement('<a><b>123</b></a>');
  var_dump($xml);
  echo $xml ? "true": "false";

or

  $xml=new SimpleXMLElement('<a><b></b></a>');
  var_dump($xml);
  echo $xml ? "true": "false";

however the second returns false even though an XMLSimpleElement object is returned. I have the same issue with an xml doc with namespaces everywhere.

it means I cannot test for a failed XML parsing as if (!xml) returns false

but $xml->childen($namespace) does not.

Please advise TIA Ephraim

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
Ephraim
  • 199
  • 1
  • 2
  • 18

3 Answers3

1

I can't reproduce your issue but I'll try to provide a couple of hints.

First, here's the rule when converting objects to booleans:

When converting to boolean, the following values are considered FALSE:
[...] the special type NULL (including unset variables)
[...] SimpleXML objects created from empty tags

Every other value is considered TRUE (including any resource).

Second, the SimpleXMLElement constructor always returns an object but it can throw a warning and an exception.

So these are the possibilities:

// Casts as TRUE because it's an object
$xml=new SimpleXMLElement('<a><b>123</b></a>');
var_dump($xml, (bool)$xml);
unset($xml);

// Casts as FALSE because it's an SimpleXMLElement object for an empty tag
$xml=new SimpleXMLElement('<a />');
var_dump($xml, (bool)$xml);
unset($xml);

// Casts as FALSE because the $xml variable was never set sucessfully so it's not even set
try{
    $xml=new SimpleXMLElement('');
}catch(Exception $e){
}
var_dump($xml, (bool)$xml); // Notice: Undefined variable: xml
unset($xml);
Álvaro González
  • 142,137
  • 41
  • 261
  • 360
0

Objects in PHP (5+) evaluate to TRUE, always.

The one exception are SimpleXML objects created from empty tags - see http://php.net/manual/en/language.types.boolean.php

$xml = new SimpleXMLElement('<b></b>');

qualifies as such a FALSE SimpleXML object (FALSE === (bool) $xml;).

However

$xml = new SimpleXMLElement('');

Throws an exception and will halt your program if not caught. If caught, $xml is not set.

hakre
  • 193,403
  • 52
  • 435
  • 836
0

You can find everything that evaluates to true/false on http://www.php.net/manual/en/language.types.boolean.php (find "When converting to boolean, the following values are considered FALSE:")

Creating a SimpleXMLElement object will throw an exception if it fails. Following code should do what you need:

try
{
    $xml=new SimpleXMLElement('');
    var_dump($xml);
    echo 'true';
}
catch
{
    echo 'false';
}

To evaluate to true/false, you might be looking into ===, to explicitly evaluate to false.

$test = '';
echo $test ? 'true' : 'false'; // will output false
echo $test !== false ? 'true' : 'false'; // will output true
matthiasmullie
  • 2,063
  • 15
  • 17