1
我正在嘗試以XML格式啓用粘滯類的表格內容。使用XSLTProcessor從HTML中提取一個表格
我的PHP代碼:
<?php
// Load the XML source
$xml = new DOMDocument;
$out = $xml->load("collection.html");
$xsl = new DOMDocument;
$xsl->load('collection.xsl');
// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules
$xml = $proc->transformToXML($xml);
$xml = simplexml_load_string($xml);
print_r($xml);
?>
而且collection.html HTML是:
<table>
<thead>
<tr>
<th>A</th>
</tr>
<tbody>
<tr>
<td>B</td>
</tr>
</tbody>
</thead>
</table>
<table class="sticky-enabled">
<thead><tr><th>Date</th><th>Time</th><th>Location</th><th>Tracking Event</th> </tr></thead>
<tbody>
<tr class="odd"><td>16-04-2013</td><td>19:20</td><td>International Hub</td><td>Forwarded for export</td> </tr>
<tr class="even"><td>16-04-2013</td><td>18:53</td><td>International Hub</td><td>Received and processed</td> </tr>
<tr class="odd"><td>15-04-2013</td><td>17:28</td><td>Manchester Piccadilly Depot</td><td>Collected from customer</td> </tr>
<tr class="even"><td>15-04-2013</td><td>00:00</td><td>WDM Online</td><td></td> </tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>A</th>
</tr>
<tbody>
<tr>
<td>B</td>
</tr>
</tbody>
</thead>
</table>
最後collection.xsl是:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<output>
<xsl:for-each select="table[@class='sticky-enabled']/tbody/tr">
<tracking>
<date><xsl:value-of select="td[1]" /></date>
<time><xsl:value-of select="td[2]" /></time>
<event><xsl:value-of select="td[3]" /></event>
<extra><xsl:value-of select="td[4]" /></extra>
</tracking>
</xsl:for-each>
</output>
</xsl:template>
</xsl:stylesheet>
如果我跑這則$ xml是空的。如果我編輯collection.html並刪除第一個和最後一個表(即只留下我想要訪問的表),那麼它就可以工作。我懷疑問題是因此:
<xsl:for-each select="table[@class='sticky-enabled']/tbody/tr">
謝謝你的回覆。我很感激。我應該提到我正在編寫此代碼,以便最終可以從外部站點上的表中提取數據。我無法控制這張桌子。 – Chris
也許我可以通過另一種方法提取啓用粘性的表,然後使用DOMDocument來處理表? – Chris
你如何提取表格?整個文件或身體是否完整?你可以改變它。如果你可以提取你想要轉換的表格,那麼這也可以。 –