如何使用PHP DomDocument获取规范值? [英] How do I obtain the canonical value using PHP DomDocument?

查看:132
本文介绍了如何使用PHP DomDocument获取规范值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

I need to get the canonical href value using Dom. How do I do this?

推荐答案

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

There are multiple ways to do this.

使用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文件,则需要更多代码,但是它们将显示您需要的大部分结构。

In both examples, more code is required if you're parsing an entire HTML file, but they demonstrate most of the structure that you'll need.

此答案修改的代码和关于Dom 的文档。

Code modified from this answer and the documentation on Dom.

这篇关于如何使用PHP DomDocument获取规范值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆