简单 Dom 解析器 Returns 通过 Ajax 清空

Simple Dom Parser Returns Empty via Ajax

我正在使用 Simple HTML Dom Parser 更正输出中的某些链接以取得良好效果,但在通过 Ajax 调用内容时发现了一些奇怪的行为。我在 WordPress 网站上使用解析器,因此将 $content 变量输入以下函数:

function add_trailing_slash( $content ) {

    $content = str_get_html( $content );
    if( $content ):
        foreach( $content->find('a') as $a ):

            if( isset( $a->href ) && '' !== $a->href && '#' !== $a->href ):

                // replace http with https on all link hrefs
                $a->href = str_replace('http:', 'https:', $a->href);

                // checks if link lacks trailing slash and appends it if no extension (file)
                $ext = pathinfo( $a->href, PATHINFO_EXTENSION );
                if( '/' !== substr( $a->href, -1 ) && ! $ext ) $a->href = $a->href . '/';

            endif;

        endforeach;
    endif;
    return $content;
}

当使用 add_filter( 'the_content', 'add_trailing_slash' ) 添加到 the_content 过滤器时效果很好,甚至当像 return add_trailing_slash( $output ) 那样直接调用时,但是,当我通过 Ajax 调用相同的函数时,我得到一个 'success' 响应,但它完全是空的。仍然是陌生人,我发现如果我 return 通过 wpautop( $output ) 的输出它回来就好了。 wpautop (link) 本质上是一堆 preg_replace 函数,用 <p> 标签替换双换行符所以我通过 return preg_replace('<blah>', '', $content) 测试了我的输出=] 成功了!

哦,我还测试了从上面的 add_trailing_slash() 函数中删除我的所有更改,但同样的问题仍然存在,所以我猜想 str_get_html( $content ) 解析输入的方式导致它无法播放Ajax 回调很好。但为什么 preg_replace 使其 return 可用?

function add_trailing_slash( $content ) {

    $content = str_get_html( $content );
    return $content;
}

我想知道是否还有其他人遇到过这个问题,我是否遗漏了一些东西,这是预料之中的,还是这是一个错误?我可以留在我的 preg_replace 中,它看起来 'fix' 是问题,但感觉有点像 hack。

我唯一想到的是当你做 $content = str_get_html( $content );结果你得到了一个对象。也许当它通过 wp 函数时,它会像字符串一样被解释,但是当你 json_encoding 它时,可能会出错并杀死它。您可以尝试将其强制转换为带

的字符串
return (string) $content;

或尝试使用

// Dumps the internal DOM tree back into string
$str = $html->save();

如文档中所述