本文介绍了我如何使用php和dom获取第一,第二和第三TD值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的表:
<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的内容.但是我管理不了.
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
}
}
我想要这样: $ value ['firsttd'],$ value ['secondtd'],$ value ['thirdtd']
推荐答案
您可以使用 for
将结果限制为 td
上的前3个项目:
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.
您可以使用以下命令输出结果 $ value
:
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";
}
这篇关于我如何使用php和dom获取第一,第二和第三TD值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!