php - 使用 PHP DOM 获取 html 页面的 <h2> 值?

标签 php

我有一个 HTTP (craigslist) 链接的变量 $link , 并将内容放入 $linkhtml .在这个变量中是 craigslist 页面的 HTML 代码,$link .

我需要提取 <h2> 之间的文本和 </h2> .我可以使用正则表达式,但我如何使用 PHP DOM 来做到这一点?到目前为止我有这个:

$linkhtml= file_get_contents($link);
$dom = new DOMDocument;
@$dom->loadHTML($linkhtml);

接下来我要做什么来放置元素<h2>的内容?进入 var $title

最佳答案

如果 DOMDocument 对您来说看起来难以理解/使用,那么您可以尝试 PHP Simple HTML DOM Parser它提供了有史以来最简单的 html 解析方法。

require 'simple_html_dom.php';
$html = '<h1>Header 1</h1><h2>Header 2</h2>';
$dom = new simple_html_dom();
$dom->load( $html );
$title = $dom->find('h2',0)->plaintext; 
echo $title; // outputs: Header 2

关于php - 使用 PHP DOM 获取 html 页面的 <h2> 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10524838/

相关文章:

php - mysql 查找未完成的条目

php - Slack 正在打印原始 JSON 而不是样式化消息

php - 寻找比index.html更好的索引

php - 如何用php和Codeigniter存储搜索条件?

批处理文件中的 PHPUnit 设置

PHP 仅在命令行模式下抛出 XDebug 错误

php - MySQL之类的查询不起作用?

php - 在数字上强制保留 4 个小数位而不将其类型更改为字符串

php - WooCommerce 结帐字段设置和自定义 Hook

PHP GD调整透明图像大小给黑色边框