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

Link to comment
Share on other sites

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.";
        }
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.