how can i get first, second and third TD values using php and dom

随声附和 提交于 2021-02-07 04:07:24

问题


i have a table such this:

<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>

And I want to get td's content. But I could not manage it.

    $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
    }

}

i want like this: $value['firsttd'] , $value['secondtd'], $value['thirdtd']


回答1:


You can use a for to limit the result to only the first 3 items on the 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);

Live DEMO.

And you can output the resulting $value with:

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

Based on your comment, you could use a multidimensional array like this:

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";
}



回答2:


It's much easier to do with 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],
);


来源:https://stackoverflow.com/questions/18004204/how-can-i-get-first-second-and-third-td-values-using-php-and-dom

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!