首页 > 解决方案 > PHP,在具有相同名称的 HTML 标签之间提取数据

问题描述

我有这个 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

谢谢你。

标签: phphtmlregexdomextract

解决方案


假设您可以识别特定的数据块,因为这假设您只是查看每个<div>标签以及每个标签的相同内容。

它只是getElementsByTagName()在各个级别使用<a>标签来获取数据,它假设 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>

推荐阅读