php DOM空字符串提供作为输入错误
问题描述:
我意识到这个问题之前已经问过,因为我已经经历了10多个类似的问题,但我想弄清楚我做错了什么。我不断收到错误警告:DOMDocument :: LoadHTML:空字符串提供作为输入。这是令人沮丧的,因为我甚至使用极其简单的表达式(通常是通用的,直接从论坛没有编辑)得到这个错误,我意识到这是由于我是PHP和DOMDocument函数的新手。php DOM空字符串提供作为输入错误
下面是一个例子函数,返回错误:
function breadcrumb_json() {
$dom = new DOMDocument();
$libxml_previous_state = libxml_use_internal_errors(true);
// Populate $dom with $content, making sure to handle UTF-8.
// Also, make sure that the doctype and HTML tags are not added to our
// HTML fragment. http://stackoverflow.com/a/22490902/3059883
$dom->loadHTML($html);
// Create an instance of DOMXpath.
$xpath = new DOMXpath($dom);
// Get images then loop through and add additional classes.
$imgs = $xpath->query("//img");
foreach ($imgs as $img) {
$existing_class = $img->getAttribute('class');
echo $existing_class;
}
}
add_action('wp_footer', 'breadcrumb_json');
你可以从我的聪明函数名字大概看到我最终试图为我的网页上的面包屑创造JSON + LD结构化数据。底线是,无论我如何尝试此功能,我都会收到空字符串错误。我的$ html变量是否需要用我的网站特定的东西替换?是否有我需要的全局变量,我错过了?这是在Wordpress(版本4.8.2),以防万一。
感谢您在正确的方向轻推!
答
您的$html
变量未定义。
PHP没有Javascript这样的词汇范围,所以你在breadcrumb_json()
函数之外定义的任何东西都不是函数内部已知的。您需要将$html
传递给breadcrumb_json($html)
。
谢谢。这非常基本,但正是我需要的。 – TomM0419
@Tom如果需要,我可以扩展它,但是您需要告诉我您希望我扩展的部分。 – Gordon