I have recently updated my PHP from 5.3 to 5.5 and got this bug.
My XML is:
<search-response>
...
...
<results-count>12345</results-count>
</search-response>
If I check for if $value is empty, it always is. While this worked in PHP 5.3. Did they change something in the empty()
method?
$contents = file_get_contents(dirname(__FILE__). '/dummy.xml');
$xml = new SimpleXMLElement($contents);
function xpath_val($source_xml, $argument_array) {
$result = array();
foreach($argument_array as $k => $v){
$node = $source_xml->xpath($v[0]);
if (empty($node)) {
$value = $node;
} else {
$value = $node[0];
}
if (empty($value)) {
$nodeval = '';
} else {
$nodeval = strval($value);
}
echo $nodeval;
}
}
$arr = array();
$arr['info'] = xpath_val($xml,array(
'count' => array('/search-response/results-count','integer')
));
var_dump($arr);
edit return $nodeval; instead of echo $nodeval; gives:
array(1) {
["info"]=>
string(0) ""
}
Yes, there was a change for the status of empty
for a SimpleXMLElement beginning with 5.4. Before 5.4 the SimpleXMLElement representing the same element as from object access behaved the same with empty($element)
as it did for those from the SimpleXMLElement::xpath()
method result array.
Since PHP 5.4 the elements as xpath result objects are now always true
when checked with empty
(other accesses didn't change empty behaviour).
You're most likely not looking for empty($value)
therefore but for !strlen($value)
.
Take care that SimpleXMLElement comes with a lot of magic, var_dump
and print_r
for example don't work well with it. And also empty
has some nuances.
If you test for the value of an existing SimpleXMLElement, cast it to string.
If you want to verify if the element exists, check that it's self-reference is not NULL.
There are also some bug-reports about the break on 5.3 -> 5. 4 version change with SimpleXML: