在PHP中抓取当前页面上的H1元素


Scrape an H1 element on the current page in PHP

我目前正在使用Wordpress。我有一个钩子,它在<title>属性填充用户在面板中输入的文本之前运行。

现在,我想将每个页面的默认标题设置为等于当前页面上的<h1>属性文本值。我正在使用的钩子的回调函数片段如下:

if (!$seoTitle) {
    $seoTitle = '<....>';
}
return $seoTitle;

我希望seoTitle默认为当前页面上的<h1>元素文本。这可行吗?我怎样才能做到这一点?

我不完全确定如何获得HTML,但可以使用内置的DOM解析器进行解析。

<?php
$html = "<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading one</h1>
<p>This is a paragraph.</p>
<h1>This is a Heading two</h1>
<p>This is a paragraph.</p>
<h1>This is a Heading three</h1>
<p><a href='testwww'> This is a paragraph.</a></p>

</body>
</html>";
$dom = new DOMDocument();
$dom->loadHTML($html);
//If you want to get it from a website you could do the following:
//$dom->loadHTML(file_get_contents('http://www.w3schools.com/'));
// iterate through the html to get all h1 text
foreach($dom->getElementsByTagName('h1') as $heading) {
    $h1 = $heading->nodeValue;
    echo $h1 . "<br>";
}
?>

假设您在一个变量中包含HTML内容,并在页面完全加载后执行此操作,请查看以下示例:

<?php
$htmlContent = '<html><body><h1>HELLO</h1></body></html>'; // change this to what you need
$seoTitle = preg_replace('/(.*)<h1>([^>]*)<'/h1>(.*)/is', '$2', $htmlContent);
echo $seoTitle; // will output: HELLO
?>
echo "<h1>".(string)$seoTitle."</h1>";

应该有效。您也可以跳出php?>,然后键入正则html,然后在想要回显变量时插入。