在 PHP 中使用 DOMDocument 获取 href 值

Get href value with DOMDocument in PHP

file_get_contents 之后,我收到了这个 HTML:

<h1>
    <a href="blablabla.html">Manhattan Skyline</a>
</h1>

我只想得到 blablabla.html 部分。

如何使用 PHP 中的 DOMDocument 功能解析它?

重要提示:我收到的 HTML 包含多个 <a href="...">.

我尝试的是:

$page = file_get_contents('https://...');
$dom = new DOMDocument();
$dom->loadHTML($page);
$xp = new DOMXpath($dom);

$url = $xp->query('h1//a[@href=""]');
$url = $url->item(0)->getAttribute('href');

感谢您的帮助。

h1//a[@href=""] 正在寻找具有 href 属性的 a 元素,其值为空字符串,而您的 href 属性包含除空字符串以外的其他内容字符串作为值。


如果这是整个文档,那么您可以使用表达式 //a.

否则,h1//a 也应该有效。

如果您需要 a 元素具有具有任何类型值的 href 属性,您可以使用 h1//a[@href].

如果 h1 不在文档的根目录下,您可能需要使用 //h1。所以最后一个例子会变成 //h1//a[@href].