Jump to content

How to validate a value when parsing children with SimpleXML


sKunKbad

Recommended Posts

When parsing an element's children with simpleXML, the children are returned as an array of objects, and I'd like to be able to get the actual value for validation, but haven't successfully done so. For instance:

 

foreach( $xml->sub_key->children() as $element_name => $value )
{
var_dump( $value );
}

Output here shows that $value is something like:

object(SimpleXMLElement)#20 (1) {

  [0]=>

  string(1) "1"

}

I've tried to access [0] by $value->0 and $value->{'0'} but that doesn't work. What I'm trying to do, for instance, is use is_numeric() to test the $value, but $value is always an object, so is_numeric won't work on it directly. How can I test with is_numeric()?

 

Actually, even when I try to test the element directly it is an object:

 

if( ! is_numeric( $xml->sub_key->child ) )
{
echo gettype( $xml->sub_key->child );
}

//returns object

You cast the objects to the data type you want.  If you are doing this so you can test against is_numeric, you would have to cast to a string, then test.

 

foreach( $xml->sub_key->children() as $child )  
{
$value = (string)$child;
        if (is_numeric($value)) {
            echo "$value is numeric";
        } else {
            echo "$value is not numeric.";
        }
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.