php - 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
谢谢你。
解决方案
假设您可以识别特定的数据块,因为这假设您只是查看每个<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>
推荐阅读
- android - NativeActivity vs NDK JNI vs SDK
- javascript - 条纹结帐,付款后获取数据
- python-3.x - 加快 difflib 查找 get_close_matches() 函数
- flutter - 我正在使用 Flutter 文本字段(不是文本表单字段)制作温度转换器应用程序我需要限制多个点和多个符号 (+ - )?
- go - 使用泛型:运算符 == 未为 T 定义
- python - 安装 Nashpy 库时缺少 requirements.txt
- java - Android:BLE清除取消自动连接
- python - django-admin 显示错误,我该如何解决?
- python - MSINT - 图像分类 - 值错误不兼容的形状
- git - ¡实时站点中的GITLAB和GIT存储库