首页 > 解决方案 > 问:如何在不使用 XPath 的情况下从网页中查找部分

问题描述

我需要从网页中提取一个部分。我需要一个带有 DOM API 而没有 XPath 的版本。这是我的版本。需要从“Latest Distributions”中提取并在浏览器中显示信息。

<?php
$result = file_get_contents ('https://distrowatch.com/');

libxml_use_internal_errors(true);

$doc = new DOMDocument();
$doc->loadHTML($result);
$xpath = new DOMXPath($doc);

$node = $xpath->query('//table[@class="News"]')->item(0);

echo $node->textContent;

标签: phphtmldomdomdocument

解决方案


这看起来很简单,但是这样做而不是 XPath 是浪费时间。

<?php
$result = file_get_contents ('https://distrowatch.com/');

libxml_use_internal_errors(true);

$doc = new DOMDocument();
$doc->loadHTML($result);
foreach ($doc->getElementsByTagName("table") as $table) {
    if ($table->getAttribute("class") === "News") {
        echo $table->textContent;
        break;
    }
}

推荐阅读