Store boolean value in xml document and read using PHP SimpleXML
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)($statu开发者_高级运维sXml->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:
- XML data is always a string
- PHP type casting rules can be pretty counter-intuitive
... 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:
- SimpleXML objects created from empty tags: FALSE
- Every other value: TRUE
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).
You are not grabbing 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;
}
}
This is quite old but just in case someone is looking for an answer. You could just use:
<example is-true=1>
or
<example is-true=0>
This should work fine.
Note using <example is-true="0">
will return true if you use an an if statement on it.
精彩评论