如何使用 SimpleXML 检查元素是否存在? [英] How to check if element exists with SimpleXML?
本文介绍了如何使用 SimpleXML 检查元素是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下内容(简化的 XML):
I have the following (simplified XML):
<?xml version="1.0" encoding="UTF-8" ?>
<products>
<product>
<artnr>xxx1</artnr>
</product>
</products>
以及以下(再次简化的 PHP 代码):
And the following (again simplified PHP code):
$xml= @simplexml_load_file($filename);
foreach ($xml->product as $product) {
if (!$this->validate_xml_product($product)) {
continue;
}
}
function validate_xml_product($product)
{
if (!property_exists('artnr', $product)) {
// why does it always validate to true?
}
}
由于某种原因,产品从未通过验证.
For some reason the product never validates.
property_exists 不是判断$product 中是否有artnr 元素的正确方法吗?
Isn't property_exists the correct way of finding out whether there is an artnr element in $product?
推荐答案
代码中参数的顺序颠倒了.正确的是首先是对象然后是属性名称:
The order of parameter in your code is reversed. Correct is first the object then the property-name:
if (!property_exists($product, 'artnr')) {
显然这仅适用于真实"属性.如果属性是使用 __get
-Method 实现的,这也不起作用.
And apparently this only works for "real" properties. If the property is implemented using the __get
-Method this won't work either.
这篇关于如何使用 SimpleXML 检查元素是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文