您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“php中table內(nèi)容如何轉(zhuǎn)成數(shù)組”,內(nèi)容簡(jiǎn)而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“php中table內(nèi)容如何轉(zhuǎn)成數(shù)組”這篇文章吧。
php table內(nèi)容轉(zhuǎn)數(shù)組的方法:1、創(chuàng)建一個(gè)PHP示例文件;2、通過“function tdToArray($table) {...}”方法將HTML表格的每行每列轉(zhuǎn)為數(shù)組即可。
本文操作環(huán)境:windows7系統(tǒng)、PHP7.1版、DELL G3電腦
php 正則匹配網(wǎng)頁html 中的table 把內(nèi)容轉(zhuǎn)化成數(shù)組
在對(duì)接京東vop 的時(shí)候,在京東返回規(guī)格屬性的時(shí)候,返回的是 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">主材質(zhì) </td> <td>PP </td> </tr> <tr> <td class="tdTitle">規(guī)格 </td> <td>800mm*445mm*225 </td> </tr> </table>';
如上的表格 ,預(yù)覽為
接下來便是進(jìn)行提取, 提取思路是 利用正則把<table><td> ,<tr>等標(biāo)簽先刪除掉。
先貼代碼
//php采集table表格數(shù)據(jù)(將HTML表格的每行每列轉(zhuǎn)為數(shù)組) 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 標(biāo)記 $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) { // 自己可添加對(duì)應(yīng)的替換 $td = explode('{td}', $tr); array_pop($td); $td_array[] = $td; } return $td_array; }
用debug 走流程,觀察每一步,具體就不詳述,放一張最后$table的變量
經(jīng)過array_pop之后的變量
是 如下
上面的\r\n 是為了區(qū)分加的換行, 可以用str_replace 替換 ,另外還有標(biāo)題也可以替換, 如下
最終效果
以上是“php中table內(nèi)容如何轉(zhuǎn)成數(shù)組”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。