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

标签 php xml xpath screen-scraping

我需要从网站上的表格中抓取一些网站数据,并创建一个将由应用程序使用的 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 feed:

<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>

最佳答案

通过 XSLT 转换运行它:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <xsl:for-each select="table/tbody/tr">
      <train>
        <route><xsl:value-of select="td[@class='resRoute']" /></route>
        <direction><xsl:value-of select="td[@class='resDir']" /></direction>
        <due><xsl:value-of select="td[@class='resDue']" /></due>
      </train> 
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

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

相关文章:

java - 在 MAPPER XML 中的 SELECT 语句中传递多个参数

R 中带有嵌套兄弟数据框的 xml

xpath - XPath中的 "element"和 "//element"有什么区别?

php - Laravel welcome.blade.php 无法正确加载

php - 在 zend 框架中构建搜索查询

c# - 来自 WebService 的未经净化的 XML,如何净化

php - 使用 PHP DomDocument 抓取格式错误的 HTML

php - 从数据库中获取记录时的动态行跨度

php - 带有图像的 ACF 帖子,与 html 和 css 一起使用

.net - 使用 Linq to XML 时出现 NullReferenceException