簡體   English   中英

使用 PHP (DOMDocument?) 將 HTML 表格轉換為 XML

[英]Convert HTML table to XML using PHP (DOMDocument?)

我希望將以下 HTML 表標記轉換為 XML 格式。

<table class='tbl-class'>
  <thead>
    <tr>
      <th>Island</th>
      <th>Number of nights</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Guadeloupe</td>
      <td>1</td>
    </tr>
    <tr>
      <td>Antigua</td>
      <td>5</td>
    </tr>
  <tbody>
</table>

理想情況下,我希望 XML 輸出是這樣的:

<location>
  <island>Guadeloupe</island>
  <nights>1</nights>
</location>
<location>
  <island>Antigua</island>
  <nights>5</nights>
</location>

我目前正在嘗試使用 DOMDocument 來執行此操作,但幾乎沒有任何使用它的經驗。 到目前為止,我已經完成了以下工作: - 我認為我需要在 foreach 循環中做更多的事情,但不確定是什么..

$doc = new DOMDocument();
$doc->load($convertedString);
$classname = 'tbl-class';
$finder = new DomXPath($doc);
$nodes = $finder->query("//*[contains(@class, '$classname')]");

foreach ($nodes as $node) {
  $node->parentNode->removeChild($node);
}

$convertedString = $doc->saveHTML();

我發現使用 SimpleXML 顧名思義 - 更簡單。 此代碼讀取 XML 並像您一樣 - 找到<table>元素。

然后使用foreach()它使用 SimpleXML 將元素層次結構引用為對象的能力,因此$table[0]->tbody->tr引用表的<tbody>部分中的<tr>元素。

然后它將每個<td>元素與$headers ...

$xml= simplexml_load_string($convertedString);

$classname = 'tbl-class';
$table = $xml->xpath("//*[contains(@class, '$classname')]");

$headers = ["island", "nights"];
$out = new SimpleXMLElement("<locations />");
foreach ( $table[0]->tbody->tr as $tr ){
    $location = $out->addChild("location");
    $key = 0;
    foreach ( $tr->td as $td )  {
        $location->addChild($headers[$key++], (string)$td);
    }
}

echo $out->asXML();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM