我有一张这样的表:
<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']
答案 0 :(得分:4)
您可以使用for
将结果限制为td
上的前3项:
$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
:
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";
}
答案 1 :(得分: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],
);