gpt4 book ai didi

php - 从解析的 HTML 表构建数组

转载 作者:行者123 更新时间:2023-11-29 09:13:21 24 4
gpt4 key购买 nike

我刚刚开始尝试自学 PHP,需要一些帮助。我试图使用 DOM 解析 HTML 表以将结果放入 MySQL 数据库中,但遇到问题。我可以用这个来回显表格的每一行:

foreach ($html->find('table') as $table)
foreach ($table->find("tr") as $rows)
echo $rows."<br />";

数据具有以下结构:

<tr>
<a href=http://some link>text1</a>
<td class="...">text2</td>
<td class="...">text3</td>
<td class="...">text4</td>
</tr>

我试图将链接和 text1-4 放入数组中,但无法弄清楚。任何帮助,将不胜感激。--编辑--
这是我试图分解的表格布局。

<tr>
<th class="school first">
<ahref="/local/team/home.aspx?schoolid=472d8593">Aberdeen</a>
</th>
<td class="mascot">Bulldogs</td>
<td class="city">Aberdeen</td>
<td class="state last">MS</td>
</tr>

jnpcl 的回答给了我这个

  ROW
TEXT: Bulldogs
TEXT: Aberdeen
TEXT: MS

但没有链接。我最初的问题可能不够具体,但是,就像我说的,我正在努力学习,而且我通常是通过跳进泳池的深处来实现的。

最佳答案

更新:现在应该可以使用 OP 更新的示例代码。

这应该能让你继续:

表数组.php

<?php
// SimpleHTMLDom Library
require_once('lib/simple_html_dom.php');

// Source Data
$source = 'table-array-data.htm';

// Displays Extra Debug Info
$dbg = 1;

// Read DOM
$html = file_get_html($source);

// Confirm DOM
if ($html) {
// Debug Output
if ($dbg) { echo '<pre>'; }

// Loop for each <table>
foreach ($html->find('table') as $table) {

// Debug Output
if ($dbg) { echo 'TABLE' . PHP_EOL; }

// Loop for each <tr>
foreach ($table->find('tr') as $row) {

// Debug Output
if ($dbg) { echo ' ROW' . PHP_EOL; }

// Loop for each <th>
foreach ($row->find('th') as $cell) {

// Look for <a> tag
$link = $cell->find('a');

// Found a link
if (count($link) == 1) {

// Debug Output
if ($dbg) { echo ' LINK: ' . $link[0]->innertext . ' (' . $link[0]->href . ')' . PHP_EOL; }
}

}

// Loop for each <td>
foreach ($row->find('td') as $cell) {

// Debug Output
if ($dbg) { echo ' CELL: ' . $cell->innertext . PHP_EOL; }
}
}
}
// Debug Output
if ($dbg) { echo '</pre>'; }
}
?>
<小时/>

table_array_data.htm

<table>
<tr class="first">
<th class="school first"><a href="/local/team/home.aspx?schoolid=472d8593-9099-4925-81e0-ae97cae44e43&amp">Aberdeen</a></th>
<td class="mascot">Bulldogs</td>
<td class="city">Aberdeen</td>
<td class="state last">MS</td>
</tr>
</table>
<小时/>

输出

TABLE
ROW
LINK: Aberdeen (/local/team/home.aspx?schoolid=472d8593-9099-4925-81e0-ae97cae44e43&)
CELL: Bulldogs
CELL: Aberdeen
CELL: MS

关于php - 从解析的 HTML 表构建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4865838/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com