php - 未定义的属性:DOMDocument::$tagName

标签 php wordpress

我在 WP 的 debug.log 文件中收到以下错误。

PHP 注意:未定义的属性:DOMDocument::$tagName in .../wp-content/themes/theme-name/libs/oi/functions.php on line 441

PHP 注意:尝试在第 441 行的 .../wp-content/themes/theme-name/libs/oi/functions.php 中获取非对象的属性

function oi_display_hierarchy( $nav_menu, $args )
{
    if( ! is_single() )
    {
        return $nav_menu;
    }

    $menuXML = new SimpleXMLElement( $nav_menu );
    list($current) = $menuXML->xpath( "//li[contains(@class,'current-menu-parent')]" );
    if( !empty( $current ) )
    {
        $node = dom_import_simplexml($current);
        while($node)
        {
            $node = $node->parentNode;
            if( $node->tagName == 'li' ) // 441 - The problem line
            {
                $classes = $node->getAttribute('class');
                $node->setAttribute('class', $classes . ' current-menu-ancestor current-menu-parent current_page_parent current_page_ancestor');
            }
        }
    }

    return str_replace('<?xml version="1.0"?>', '', $menuXML->asXML());
}
add_filter('wp_nav_menu', 'oi_display_hierarchy', 11, 2);

任何想法可能是这里的问题?

最佳答案

您正在尝试获取当前 DOMElement 上一行的对象父节点:

$node = $node->parentNode;

所以在那之后$node将更改为 DOMNode ( DOMElement 继承 DOMNode )。 tagName属性不是 DOMNode 定义的一部分,它特定于 DOMElement - 这就是它抛出错误的原因。

xml 中的所有内容都是一个节点 - 文本、行、注释...所以 DOMNode 可以 一个标签,但它也可以是其他东西。因此,我们需要使用以下内容检查节点的类型:
if($node->nodeType == XML_ELEMENT_NODE) { // Node is a DOMElement

这样我们就可以确定 $node 是 DOMElement ,然后可以安全使用 tagName属性(property)。

关于php - 未定义的属性:DOMDocument::$tagName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32627939/

相关文章:

php - Model::unguard() 在 Laravel 5 的数据库种子文件中做了什么?

php - 正确显示 MySQL "GROUP BY"结果

php - CodeIgniter 3.0 发生数据库错误

php - Wordpress cron wp_schedule_single_event – 操作并不总是有效

php - 将实时站点移至本地 - 问题识别数据库

php - 函数未返回 "functions.php"中的值

php - 在mysql和php中使用sum和group by将一张表数据插入到不同的表中

css - css 注释中的 "/* =SomeText"是什么

php - 使用命名空间时找不到 SimpleXMLElement

php - 不只是另一个无法连接php到mysql