How do you store boolean values in an XML document such that you can read them using PHP's 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 it:
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 always gets read as true. I've tried "0", empty string, "false", and a bunch of other ideas but nothing has worked. I thought empty string should would because of what I found in this doc: http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting
Considering that:
... I would not rely on automatic type juggling. Simply, define a syntax you are comfortable with, cast to string when reading and write your own code to cast to 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, if you are curious about how to make (bool)
work, you are basically dealing with objects so this is the rule that applies when casting to boolean:
That means that you will only get FALSE
with <investigating />
(and TRUE
with absolutely anything else). A trick I can think of to widen the range of possible TRUE values is to perform double casting:
(bool)(string)$xml->investigating
Update: don't forget to debug with var_dump()
. If you use echo
you'll find that TRUE
boolean casts to '1'
string and FALSE
to ''
(empty string).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With