在對接京東vop 的時候,在京東返回規格屬性的時候,返回的是 html格式的樣式,例
$date=' <table cellpadding="0" cellspacing="1" width="100%"border="0" class="Ptable"> <tr> <th class="tdTitle" colspan="2">主體 </th> <tr> <tr> <td class="tdTitle">品牌 </td> <td>好孩子 </td> </tr> <tr> <td class="tdTitle">主材質 </td> <td>PP </td> </tr> <tr> <td class="tdTitle">規格 </td> <td>800mm*445mm*225 </td> </tr> </table>';
如上的表格 ,預覽為
接下來便是進行提取, 提取思路是 利用正則把<table><td> ,<tr>等標簽先刪除掉。
先貼代碼
//php采集table表格數據(將HTML表格的每行每列轉為數組) function tdToArray($table) { $table = preg_replace("'<table[^>]*?>'si","",$table); $table = preg_replace("'<tr[^>]*?>'si","",$table); $table = preg_replace("'<td[^>]*?>'si","",$table); $table = str_replace("</tr>","{tr}",$table); $table = str_replace("</td>","{td}",$table); //去掉 HTML 標記 $table = preg_replace("'<[/!]*?[^<>]*?>'si","",$table); //去掉空白字符 $table = preg_replace("'([rn])[s]+'","",$table); $table = str_replace(" ","",$table); $table = str_replace(" ","",$table); $table = explode('{tr}', $table); array_pop($table); foreach ($table as $key=>$tr) {
// 自己可添加對應的替換 $td = explode('{td}', $tr); array_pop($td); $td_array[] = $td; } return $td_array; }
用debug 走流程,觀察每一步,具體就不詳述,放一張最后$table的變量
經過array_pop之后的變量
是 如下
上面的\r\n 是為了區分加的換行, 可以用str_replace 替換 ,另外還有標題也可以替換, 如下
最終效果