Store a boolean in an XML document and read using PHP SimpleXML

How do you store booleans in an XML document so that they can be read using the PHP SimpleXML class?

I have the following XML document:

<?xml version='1.0' standalone='yes'?> <status> <investigating></investigating> <log> sample log </log> </status> 

And the following php script to read:

 if (file_exists($filename)) { $statusXml = simplexml_load_file($filename); if ($statusXml) { $investigating = (bool)($statusXml->investigating); echo $investigating; } } else { exit('Failed to open ' . $filename .'.'); } 

No matter what I put in the tag, it is always read as true. I tried "0", an empty string, "false" and a bunch of other ideas, but nothing worked. I thought an empty line should have been due to what I found in this document: http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting

+7
source share
3 answers

Given that:

  • XML data is always a string
  • PHP type selection rules can be quite inconsistent.

... I would not rely on automatic juggling. Just determine the syntax that is more convenient for you, drop it into a line when reading and writing your own code for translation into boolean.

 <?php function get_bool($value){ switch( strtolower($value) ){ case 'true': return true; case 'false': return false; default: return NULL; } } $data = '<?xml version="1.0"?> <data> <empty_tag/> <true_tag>true</true_tag> <false_tag>false</false_tag> </data> '; $xml = simplexml_load_string($data); var_dump( get_bool((string)$xml->empty_tag) ); var_dump( get_bool((string)$xml->true_tag) ); var_dump( get_bool((string)$xml->false_tag) ); 

Whatever it is, if you are interested in how to do the work (bool) , you mainly deal with objects, so this rule applies when casting to a logical one:

  • SimpleXML objects created from empty tags: FALSE
  • Each other value: TRUE

This means that you only get FALSE with <investigating /> (and TRUE with absolutely anything else). The trick I can come up with to expand the range of possible TRUE values ​​is to double cast:

 (bool)(string)$xml->investigating 

Update: Remember to debug var_dump() . If you use echo , you will find that TRUE boolean distinguishes between the string '1' and FALSE to '' (empty string).

+5
source

You do not capture the right element.

 if (file_exists($filename)) { $statusXml = simplexml_load_file($filename); if ($statusXml = simplexml_load_file($filename)) { $investigating = (bool) $statusXml->investigating[0]; echo $investigating; } } 
-one
source

It's pretty old, but just in case someone is looking for an answer. You can simply use:

 <example is-true=1> 

or

 <example is-true=0> 

This should work fine.

A note using <example is-true="0"> will return true if you use an if statement on it.

-one
source

All Articles