0

curl を使用して HTML ファイルを取得し、DOM を使用して必要なものを取得しようとしています。

私は(私の観点から)すべてを試しましたが、思い通りに機能しません。

私がこれを持っているとしましょう:

html = '<table cellpadding="0" cellspacing="0" id="uniq">
        <tr>
            <th>text</th>
            <td class="1_th">a1</td>
            <td class="1_td">b1</td>
        </tr>
        <tr>
            <th rowspan="3">text1</th>
            <td class="1_th">a2</td>
            <td class="1_td">b2</td>
        </tr>
        <tr>
            <td class="1_th">a3</td>
            <td class="1_td">b3</td>
        </tr>
        <tr>
            <td class="1_th">a4</td>
            <td class="1_td">b4</td>
        </tr>
        <tr>
            <th rowspan="2">text2</th>
            <td class="1_th">a5</td>
            <td class="1_td">b5</td>
        </tr>
        <tr>
            <td class="1_th">a6</td>
            <td class="1_td">b7</td>
        </tr>
    </table>'

これをPHPでエコーできるようにしたい:

text - a1 -b1
text1 - a2 -b2
text1 -a3 -b3
text1 -a4 -b4
text2 -a5 -b5
text2 -a6 -b6

テーブルは大きく、th15 から 20 の間の可変の行スパンがあります。MySQL にechoこれらの値を挿入したいので、そうしたいのです。

私はこれを試しました:

$dom = new DOMDocument();
@$dom->loadHTML($html);
$x = new DOMXPath($dom);
$table = $x->query('//*[@id="uniq"]')->item(0);
$rows = $table->getElementsByTagName("tr");
foreach ($rows as $row) {
    $tds = $row->nodeValue;
    echo $th;
}

気にしないで、必要なものの解決策を見つけました。助けてくれてありがとう

これは私が作ったもので、私には問題ありません:

$dom = new DOMDocument();
    @$dom->loadHTML($html);
    $x = new DOMXPath($dom); 


$table = $x->query("//*[@id='item_specification']/tr");
$rows = $table;
foreach ($rows as $row) {
 $atr_name = $row -> getElementsByTagName('td')->item(0)->nodeValue;
 $atr_val = $row -> getElementsByTagName('td')->item(1)->nodeValue;
 $cell1 = $row -> getElementsByTagName('th');
`$ifth = $cell1->length;
`if ($ifth == 1) {
$atr_cat = $row->getElementsByTagName('th')->item(0)->nodeValue;
}
  echo "{$atr_cat} - {$atr_name} - {$atr_val} <br \>";  
}
4

1 に答える 1

0

strip_tags()次のように使用してみてください。

<?php
$html = '<table cellpadding="0" cellspacing="0" id="uniq">
<tr>
<th>text</th>
<td class="1_th">a1</td>
<td class="1_td">b1</td>
</tr>
<tr>
<th rowspan="3">text1</th>
<td class="1_th">a2</td>
<td class="1_td">b2</td>
</tr>
<tr>
<td class="1_th">a3</td>
<td class="1_td">b3</td>
</tr>
<tr>
<td class="1_th">a4</td>
<td class="1_td">b4</td>
</tr>
<tr>
<th rowspan="2">text2</th>
<td class="1_th">a5</td>
<td class="1_td">b5</td>
</tr>
<tr>
<td class="1_th">a6</td>
<td class="1_td">b7</td>
</tr>
</table>';
$html = strip_tags($html);
echo $html;
?>

これが、この関数の動作中のPHPFiddleです。

出力:

text a1 b1 text1 a2 b2 a3 b3 a4 b4 text2 a5 b5 a6 b7
于 2013-01-12T18:23:14.307 に答える