我如何使用 php 从 html 视图源中获取 "rel" 属性的值?

How I get the value of "rel" attribute from the html view source using php?

我想要与搜索域关联的锚标记的 rel 属性的值。

我必须更改域 "blog.zeit.de/berlinjournal" 而不是“http://blog.zeit.de/berlinjournal/”。使用此域并找出 rel Val

@Sam Onela,代码不适用于该域。请帮我解决这个错误。

我的代码是:

$domain = 'blog.zeit.de/berlinjournal';
$handle = fopen($domain, 'r');
$content = stream_get_contents($handle);
fclose($handle);
if ((strpos($content, $domain) !== false)) {
        echo 'true'; // true if $domain found in view source content
} 

吹图搞清楚思路

创建 DOMDocument, call the loadHTML() method, then use simplexml_import_dom() to get an instance of a SimpleXMLElement, on which the xpath() 方法的实例可用于查询该锚标记。

您可能还会注意到加载 html 时屏幕上打印的警告。要将其设置为使用内部错误处理程序,请使用 libxml_use_internal_errors(true); - 感谢@dewsworld this answer.

libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTML($content);
$xml = simplexml_import_dom($doc);
$results = $xml->xpath("//a[@href='$domain']");
if (sizeof($results)) {
    echo 'rel: '.$results[0]['rel'].'<br>';
}

参见 this phpfiddle 中的演示。

更新

由于原来的URL的HTML变了,现在的需求是找到不同锚标签的rel属性,这样就可以了使用 contains() xpath 函数完成。

$searchDomain = 'rballutschinski.wordpress.com/';
if ((strpos($content, $searchDomain) !== false)) {
    $doc = new DOMDocument();
    $doc->loadHTML($content);
    $xml = simplexml_import_dom($doc);
    $results = $xml->xpath("//a[contains(@href,'$searchDomain')]");
    if (sizeof($results)) {
        $rel = $results[0]['rel'];
    }

请参阅 this phpfiddle 中的演示。