php:从html解析字符串

Joh*_*eth 3 html php parsing dom

我已经打开了一个HTML文件

file_get_contents('http://www.example.com/file.html')
Run Code Online (Sandbox Code Playgroud)

并想要解析包括"ParseThis"的行:

 <h1 class=\"header\">ParseThis<\/h1>
Run Code Online (Sandbox Code Playgroud)

如您所见,它位于h1标记内(h1文件中的第一个标记).如何获得"ParseThis"文本?

Gor*_*don 5

您可以使用DOM.

// Load remote file, supress parse errors
libxml_use_internal_errors(TRUE);
$dom = new DOMDocument;
$dom->loadHTMLFile('http://www.example.com/file.html');
libxml_clear_errors();

// use XPath to find all nodes with a class attribute of header
$xp = new DOMXpath($dom);
$nodes = $xp->query('//h1[@class="header"]');

// output first item's content
echo $nodes->item(0)->nodeValue;
Run Code Online (Sandbox Code Playgroud)

另见

标记这个CW,因为我之前已经回答了这个问题,但是我太懒了,找不到副本