Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store boolean value in xml document and read using PHP SimpleXML

Tags:

php

xml

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)($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

like image 852
Ankur Avatar asked Jun 30 '11 16:06

Ankur


1 Answers

Considering that:

  1. XML data is always a string
  2. 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).

like image 144
Álvaro González Avatar answered Oct 23 '22 19:10

Álvaro González