如何使用 PHP DomDocument 获取规范值


How do I obtain the canonical value using PHP DomDocument?

<link rel='canonical' href='http://test.com/asdfsdf/sdf/' />

我需要使用 Dom 获取规范的 href 值。我该怎么做?

有多种方法可以做到这一点。

使用 XML:

<?php
$html = "<link rel='canonical' href='http://test.com/asdfsdf/sdf/' />";
$xml  = simplexml_load_string($html);
$attr = $xml->attributes();
print_r($attr);
?>

其中输出:

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [rel] => canonical
            [href] => http://test.com/asdfsdf/sdf/
        )
)

或者,使用 Dom:

<?php
$html = "<link rel='canonical' href='http://test.com/asdfsdf/sdf/' />";
$dom = new DOMDocument;
$dom->loadHTML($html);
$nodes = $dom->getElementsByTagName('link');
foreach ($nodes as $node)
{
    if ($node->getAttribute('rel') === 'canonical')
    {
        echo($node->getAttribute('href'));
    }
}
?>

其中输出:

http://test.com/asdfsdf/sdf/

在这两个示例中,如果要分析整个 HTML 文件,则需要更多代码,但它们演示了所需的大部分结构。

根据此答案和 Dom 文档修改的代码。