Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for property's existence without getting "Node no longer exists" warning

I'm using SimpleXML. If the user input to my function is invalid, my variable $x is an empty SimpleXMLElement Object; otherwise, it has a populated property $x->Station. I want to check to see if Station exists.

private function parse_weather_xml() {
    $x = $this->weather_xml; 
    if(!isset($x->Station)) {
        return FALSE;
    }

    ...
}

This does what I want, except it returns an error:

Warning: WeatherData::parse_weather_xml(): Node no longer exists in WeatherData->parse_weather_xml() (line 183 of vvdtn.inc).

Okay, so isset() is out. Let's try this:

private function parse_weather_xml() {
    $x = $this->weather_xml; 
    if(!property_exists($x, 'Station')) {
        return FALSE;
    }

    ...
}

This behaves almost identically:

Warning: property_exists(): Node no longer exists in WeatherData->parse_weather_xml() (line 183 of vvdtn.inc)

All right, fine, I'll turn it into an exception and disregard it. I've never done this before and I'm not sure I'm doing it right, but I'll give it a try:

function crazy_error($errno, $errstr, $errfile, $errline) {
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}

...

    private function parse_weather_xml() {
        set_error_handler('crazy_error');
        $x = $this->weather_xml; 
        if(!property_exists($x, 'Station')) {
            return FALSE;
        }
        restore_error_handler();

        ...
    }

That returns its own HTML page:

Additional uncaught exception thrown while handling exception.

Original

ErrorException: property_exists(): Node no longer exists in crazy_error() (line 183 of vvdtn.inc).

Additional

ErrorException: stat(): stat failed for /sites/default/files/less/512d40532e2976.99442935 in crazy_error() (line 689 of /includes/stream_wrappers.inc).


So now I'm laughing hysterically and giving up. How can I check for the existence of a property of a SimpleXML object without getting this error in one form or another?

like image 716
75th Trombone Avatar asked Feb 26 '13 23:02

75th Trombone


1 Answers

Do you want to check if your simplexml contains a certain node or not? --> count them!

EDIT: errors when node doesn't exist --> try xpath:

if ($xml->xpath("//station")->Count()==0) echo "no station!";

will throw error if no station-node:

Say $xml is your simplexml and stationis on the top-level:

 if ($xml->station->Count()==0) echo "no station!";

If 'station' is, say, a child of <something>, you'd of course go...

... $xml->something->station->Count();
like image 102
michi Avatar answered Oct 06 '22 07:10

michi