3

我有一张这样的桌子:

<tr>
    <td><font color="#000066">ADANA</font></td>
    <td><font color="#000066">SEYHAN</font></td>    
    <td><font color="#000066">ZÜBEYDE HANIM ANAOKULU</font></td>    
    <td><font color="#000066">KURTULUŞ MAH.64011 SOK. NO:1</font></td>    
    <td><font color="#000066">(322) 453 10 60</font></td>    
    <td><font color="#000066">(322) 459 19 77</font></td> 
</tr>

我想得到td的内容。但我无法管理它。

    $xml = new DOMDocument();
    $xml->validateOnParse = true;
    $xml->loadHTML($data);

    $xpath = new DOMXPath($xml);
    $xpath = new DOMXPath($xml);
    $table =$xpath->query("//*[@id='dgKurumListesi']")->item(0);

    $rows = $table->getElementsByTagName("tr");

foreach ($rows as $row) {
    $cells = $row -> getElementsByTagName('td',0);
    foreach ($cells as $cell) {
        echo $cell->nodeValue; //il ismi
    }

}

我想要这样:$value['firsttd'] , $value['secondtd'], $value['thirdtd']

4

2 回答 2

6

您可以使用 afor将结果限制为仅在 上的前 3 个项目td

$value = array();
$table = $xpath->query("//*[@id='dgKurumListesi']")->item(0);
$rows = $table->getElementsByTagName("tr");
foreach ($rows as $row)
{
    $cells = $row->getElementsByTagName('td');
    // Keep in mind that the elements index start at 0
    // so we want 0, 1, 2 to get the first 3.
    for ($i = 0; $i < 3; $i++)
    {
        if (is_object($cells->item($i)))
            $value[] = $cells->item($i)->nodeValue;
    }
}
print_r($value);

现场演示。

您可以使用以下命令输出结果$value

foreach ($value as $item)
{
    echo $item, "<br />\n";
}

根据您的评论,您可以使用这样的多维数组:

for ($r = 0; $r < $rows->length; $r++)
{
    if (!is_object($rows->item($r)))
        continue;

    $cells = $rows->item($r)->getElementsByTagName('td');
    for ($i = 0; $i < 3; $i++)
    {
        if (is_object($cells->item($i)))
            $value[$r][$i] = $cells->item($i)->nodeValue;
    }
}

foreach ($value as $item)
{
    echo $item[0], ',', $item[1], ',', $item[2], "\n";
}
于 2013-08-01T21:18:58.953 回答
0

使用 simplexml 更容易。

$dom = simplexml_load_string($data);
$rows = $dom->xpath('/tr/td/font');
$value = array(
    'firsttd'  => (string)$rows[0],
    'secondtd' => (string)$rows[1],
    'thirdtd'  => (string)$rows[2],
);
于 2013-08-01T21:14:06.330 回答