【问题标题】:Get h2 html using Simple HTML DOM Parser使用 Simple HTML DOM Parser 获取 h2 html
【发布时间】:2019-04-28 05:43:59
【问题描述】:

我有这个代码的 HTML 网页:

<div class="col-sm-9 xs-box2">
    <h2 class="title-medium br-bottom">Your Name</h2>
</div>

现在我想使用 Simple HTML DOM Parser 来获取这个 div 中 h2 的文本值。 我的代码是:

$name = $html->find('h2[class="title-medium br-bottom"]');
echo $name;

但它总是返回错误:“

Notice: Array to string conversion in C:\xampp\htdocs\index.php on line 21
Array

我该如何解决这个错误?

【问题讨论】:

  • $name 不是字符串,你不能echo 它。试试print_r也许可以检查一下?
  • 现在使用 print_r($name),它在第 21 行的 C:\xampp\htdocs\index.php 中返回“致命错误:允许的内存大小为 134217728 字节已用尽(试图分配 65015808 字节) "
  • 您需要使用$name-&gt;plaintext。检查PHP Simple Html Dom get the plain text of div
  • 需要非常小心的一点是,在使用类属性查找数据时,页面开发人员可以轻松更改它们,并且突然您的代码无法加载这些数据。

标签: php simple-html-dom


【解决方案1】:

你可以试试Simple HTML DOM

 foreach($html->find('h2') as $element){
    $element->class;
 }

还有其他方法可以解析

方法一。

你可以使用下面的代码sn-p获取H2标签,使用DOMDocumentgetElementsByTagName

$received_str = '<div class="col-sm-9 xs-box2">
  <h2 class="title-medium br-bottom">Your Name</h2>
</div>';
$dom = new DOMDocument;
@$dom->loadHTML($received_str);
$h2tags = $dom->getElementsByTagName('h2');
foreach ($h2tags as $_h2){
  echo $_h2->getAttribute('class');
  echo $_h2->nodeValue;
}

方法2

使用Xpath可以解析它

$received_str = '<div class="col-sm-9 xs-box2">
    <h2 class="title-medium br-bottom">Your Name</h2>
</div>';
$dom = new DOMDocument;
$dom->loadHTML($received_str);
$xpath = new DomXPath($dom);
$nodes = $xpath->query("//h2[@class='title-medium br-bottom']");
header("Content-type: text/plain");
foreach ($nodes as $i => $node) {
    $node->nodeValue;
}

【讨论】:

  • 为什么你尝试使用DomDocument 更简单为什么使用OP 使用它的Simple HTML
  • @Mohammad 我已经更新了我的简单 HTML 解决方案
猜你喜欢
  • 2012-08-12
  • 2012-04-08
  • 1970-01-01
  • 2016-04-21
  • 1970-01-01
  • 2013-09-01
  • 1970-01-01
  • 2016-04-09
  • 1970-01-01
相关资源
最近更新 更多