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

dom, php

Solution

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

Problem

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']`

Original source