php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #30972 Casting an empty single node SimpleXML object to boolean returns false
Submitted: 2004-12-03 05:47 UTC Modified: 2006-03-30 04:29 UTC
From: dtorop932 at gmail dot com Assigned:
Status: Closed Package: SimpleXML related
PHP Version: 5CVS-2004-12-03 (dev) OS: GNU/Linux 2.4.27
Private report: No CVE-ID: None
 [2004-12-03 05:47 UTC] dtorop932 at gmail dot com
Description:
------------
According to http://www.php.net/manual/en/language.types.boolean.php it seems that in PHP 5 all objects should return TRUE when cast to boolean.  But if one creates a SimpleXML object from the string '<goodxml/>', then casts it to boolean, the result is FALSE.

As a comparison, running DOMDocument::loadxml() on "<goodxml/>" and casting the result to boolean returns TRUE.

This is important if one is doing what seems to be a quick test for failure of SimpleXML parsing, e.g. the following doesn't work as expected:

if (!simplexml_load_string($anyxml)) {
  return FALSE;  // this always executes, even for good XML
}

Reproduce code:
---------------
<?php
foreach (array('badxml', '<goodxml/>', '<goodxml>CONTENT</goodxml>') as $xml) {
  $dom = @simplexml_load_string($xml);
  print "\n\$dom from '$xml'\n";
  print '  ((boolean) $dom) = '; var_dump((boolean) $dom);
}
?>


Expected result:
----------------

$dom from 'badxml'
  ((boolean) $dom) = bool(false)

$dom from '<goodxml/>'
  ((boolean) $dom) = bool(true)

$dom from '<goodxml>CONTENT</goodxml>'
  ((boolean) $dom) = bool(true)


Actual result:
--------------

$dom from 'badxml'
  ((boolean) $dom) = bool(false)

$dom from '<goodxml/>'
  ((boolean) $dom) = bool(false)

$dom from '<goodxml>CONTENT</goodxml>'
  ((boolean) $dom) = bool(true)


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2004-12-04 12:40 UTC] helly@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

Use ===, !== or is_null
 [2006-03-30 04:29 UTC] simp@php.net
This bug has been fixed in CVS.

Snapshots of the sources are packaged every three hours; this change
will be in the next snapshot. You can grab the snapshot at
http://snaps.php.net/.
 
Thank you for the report, and for helping us make PHP better.

SimpleXML has its own cast handler which casts objects from empty tags to false
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Tue Mar 19 02:01:28 2024 UTC