【问题标题】:PHP, Extract data between HTML Tags that have same namePHP,在具有相同名称的 HTML 标签之间提取数据
【发布时间】:2020-11-22 02:54:01
【问题描述】:

我有这个 HTML 页面,我想提取其标签之间的数据。

<div>
    <h2>Google</h2>
    <a href="google.com/about">Google is search engine</a>
    <a href="google.com">www.google.com</a>
</div>
<div>
    <h2>Amazon</h2>
    <a href="amazon.com/about">Amazon is shopping cart</a>
    <a href="amazon.com">www.amazon.com</a>
</div>
<div>
    <h2>Yahoo</h2>
    <a href="yahoo.com/about">Yahoo is websites directory</a>
    <a href="yahoo.com">www.yahoo.com</a>
</div>

我想使用这个纯 PHP 代码:

<?php
$html = file_get_contents("demo.html");
$dom->loadHTML($html);
$nodes = $dom->getElementsByTagName('a'); 
$nodes = $dom->getElementsByTagName('h2');
foreach ($nodes as $node) {
    echo $node->nodeValue."<br>";
} ?>

如何提取数据是这样的:

Google      Google is search engine     www.google.com
Amazon      Amazon is shopping cart     www.yahoo.com
Yahoo       Yahho is websites directory www.yahoo.com

谢谢。

【问题讨论】:

标签: php html regex dom extract


【解决方案1】:

假设您可以识别特定的数据块,因为这假设您只查看每个 &lt;div&gt; 标记以及每个标记的相同内容。

它只是在各个级别使用getElementsByTagName() 来获取数据,使用&lt;a&gt; 标签,它假定有2 个标签,因此使用[0][1] 从每个标签中获取数据。

$nodes = $dom->getElementsByTagName('div');
foreach ($nodes as $node) {
    echo $node->getElementsByTagName('h2')[0]->nodeValue."/";
    $a = $node->getElementsByTagName('a');
    echo $a[0]->nodeValue."/";
    echo $a[1]->nodeValue."<br>";
}

样本给出了...

Google/Google is search engine/www.google.com<br>
Amazon/Amazon is shopping cart/www.amazon.com<br>
Yahoo/Yahoo is websites directory/www.yahoo.com<br>

【讨论】:

  • 它适用于以下错误:“注意:尝试获取非对象的属性”和这个“警告:DOMDocument::loadHTML():实体中的标记标题无效”
  • 对于实体问题,您可以在$dom-&gt;loadHTML($html); 之前添加libxml_use_internal_errors(true);。看看这是否有帮助。
猜你喜欢
  • 2019-01-05
  • 1970-01-01
  • 2015-09-26
  • 1970-01-01
  • 2021-07-10
  • 2016-11-12
  • 1970-01-01
  • 2011-09-25
  • 1970-01-01
相关资源
最近更新 更多