gpt4 book ai didi

php - 抓取 HTML 表格数据并创建 XML 文档

转载 作者:行者123 更新时间:2023-12-03 16:12:40 24 4
gpt4 key购买 nike

我需要从网站上的表格中抓取一些网站数据并创建一个将由应用程序使用的 XML 文档。

该表如下所示:

<table id="results" class="results">
<thead>
<tr>
<th scope="col" class="resRoute">Route</th>
<th scope="col" class="resDir">To</th>
<th scope="col" class="resDue sorted">Time</th>
</tr>
</thead>
<tbody>
<tr>
<td class="resRoute">263</td>
<td class="resDir">Route Name</td>
<td class="resDue">1 min</td>
</tr>
<tr>
<td class="resRoute">17</td>
<td class="resDir">Route Name</td>
<td class="resDue">2 min</td>
</tr>
</tbody>
</table>

我想创建一个如下所示的 XML 提要:
<train>
<route>263</route>
<direction>Route Name</direction>
<due>2 Min</due>
</train>
<train>
<route>17</route>
<direction>Route Name</direction>
<due>12 Min</due>
</train>

最佳答案

骇客骇客骇客骇客!

        $html = '<table id="results" class="results">
<thead>
<tr>
<th scope="col" class="resRoute">Route</th>
<th scope="col" class="resDir">To</th>
<th scope="col" class="resDue sorted">Time</th>
</tr>
</thead>
<tbody>
<tr>
<td class="resRoute">263</td>
<td class="resDir">Route Name</td>
<td class="resDue">1 min</td>
</tr>
<tr>
<td class="resRoute">17</td>
<td class="resDir">Route Name</td>
<td class="resDue">2 min</td>
</tr>
</tbody>
</table>
';

$body = explode('<tbody>', $html);

$xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><xml />");

$rows = array();
foreach (array_slice(explode('<tr>', end($body)), 1) as $row)
{
preg_match('/resRoute">([0-9]+)<\/td>/', $row, $ids);
preg_match('/resDir">([^<]+)<\/td>/', $row, $dir);
preg_match('/resDue">([^<]+)<\/td>/', $row, $due);

$node = $xml->addChild('train');

$node->addChild('route', $ids[1]);
$node->addChild('direction', $dir[1]);
$node->addChild('due', $due[1]);
}

header('Content-Type: text/xml');
echo $xml->asXML();

关于php - 抓取 HTML 表格数据并创建 XML 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7299699/

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