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?
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 station
is 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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With