HTMLParser 是一個用于解析 HTML 文檔的 PHP 類庫。要處理嵌套結(jié)構(gòu),你需要在解析過程中跟蹤當(dāng)前節(jié)點(diǎn)的層級。以下是一個簡單的示例,說明如何使用 HTMLParser 類處理嵌套結(jié)構(gòu):
composer require "simplehtmldom/simple-html-dom"
NestedHTMLParser.php
的文件,并在其中編寫以下代碼:<?php
require_once 'vendor/autoload.php';
use simplehtmldom\HtmlWeb;
use simplehtmldom\HtmlNode;
class NestedHTMLParser
{
private $html;
private $currentLevel;
private $maxLevel;
public function __construct($url, $maxLevel = 2)
{
$this->html = file_get_html($url);
$this->currentLevel = 0;
$this->maxLevel = $maxLevel;
}
public function parse()
{
$this->parseNode($this->html->find('body')[0]);
}
private function parseNode(HtmlNode $node)
{
if ($this->currentLevel > $this->maxLevel) {
return;
}
echo "Level: {$this->currentLevel}, Tag: {$node->tagName}, Content: " . $node->innertext . PHP_EOL;
foreach ($node->childNodes as $childNode) {
if ($childNode->nodeType === \simplehtmldom\HtmlWeb\str_to_int('node_element')) {
$this->parseNode($childNode);
}
}
$this->currentLevel++;
}
}
$parser = new NestedHTMLParser('https://example.com');
$parser->parse();
在這個示例中,我們創(chuàng)建了一個名為 NestedHTMLParser
的類,它接受一個 URL 和一個可選的最大層級參數(shù)。parse
方法會解析給定 URL 的 HTML 文檔,而 parseNode
方法會遞歸地處理每個節(jié)點(diǎn)。
要使用這個類,只需創(chuàng)建一個新的 NestedHTMLParser
實(shí)例并調(diào)用 parse
方法即可。例如:
$parser = new NestedHTMLParser('https://example.com');
$parser->parse();
這將輸出給定 URL 的 HTML 文檔中每個節(jié)點(diǎn)的層級、標(biāo)簽名和內(nèi)容。你可以根據(jù)需要修改這個類以處理其他類型的節(jié)點(diǎn)或執(zhí)行其他操作。