PHP-如何在每个循环中检查元素


PHP - How to check for element each loop?

我正在使用下面的循环来解析XML文件。

$link = $item->getElementsByTagName('link')->item(0)->firstChild->nodeValue;
$image = $item->getElementsByTagName('enclosure')->item(0)->getAttribute('url');

然而,有时XML项没有'enclosure'元素,我的整个页面都会失败,并出现以下错误

PHP Fatal error:  Call to a member function getAttribute() on a non-object

如果$image变量不存在,我如何在每个循环中检查元素并用静态字符串替换它?

我建议您使用xpath。使用DOMDocumentDOMXPath,您可以从DOMXPath::evaluate方法中获益匪浅,因为您可以直接获取字符串值。如果查询的元素不存在,则会得到一个空字符串(您也可以使用count()检查是否存在,如果找不到节点,则返回0)。

示例:

$item  = $doc->getElementsByTagName('itme')->item(0);
$xpath = new DOMXPath($doc);
echo "link.....: ", $xpath->evaluate('string(.//link)', $item), "'n";
echo "enclosure: ", $xpath->evaluate('string(.//enclosure[@url])', $item), "'n";

我创建了一些示例XML

<feed-me>
    <item>
        <link>http://nytimes.com/2004/12/07FEST.html</link>
        <actor class="foo" xml:space="preserve"> </actor>
    </item>
</feed-me>

输出为

link.....: http://nytimes.com/2004/12/07FEST.html
enclosure: 

如本例所示,第一个xpath表达式计算为<link>元素的文本内容。第二个表达式求值为空字符串,因为该属性不存在。

当您访问PHP代码中的对象时,从不存在的元素中获取属性的问题

$item->getElementsByTagName('enclosure')->item(0)->getAttribute('url');
                                             ^               ^
                                             |               |
                                   there is no item at       |
                                  index 0, this is NULL      |
                                                             |
                                                         NULL has no
                                                     getAttribute method
                                                        = FATAL ERROR

另一方面使用xpath表达式

 string(.//enclosure[@url])

内部表达式.//enclosure[@url]返回一个空节点列表,string()函数为其返回""(空字符串)。否则,它返回该节点列表中第一个节点(按文档顺序)的字符串值。

所有这些都使得以稳定的方式从文档中获取信息变得非常容易。不过,您必须学习一些xpath语言。但我们在这里得到了很好的支持,在Stackloverlow上也是如此。

完整示例(以及在线演示):

<?php
/**
 * PHP - How to check for element each loop?
 * @link http://stackoverflow.com/a/29452042/367456
 */
$buffer = <<<XML
<feed-me>
    <item>
        <link>http://nytimes.com/2004/12/07FEST.html</link>
        <actor class="foo" xml:space="preserve"> </actor>
    </item>
</feed-me>
XML;
$doc = new DOMDocument();
$doc->loadXML($buffer);
$xpath = new DOMXPath($doc);
$item = $doc->getElementsByTagName('itme')->item(0);
$xpath = new DOMXPath($doc);
echo "link.....: ", $xpath->evaluate('string(.//link)', $item), "'n";
echo "enclosure: ", $xpath->evaluate('string(.//enclosure[@url])', $item), "'n";
$item->getElementsByTagName('enclosure')->item(0)->getAttribute('url');