如何获取DOMDocument的子元素

时间:2018-07-23 10:14:56

标签: php html css dom

尝试从具有trtd元素的表中获取特定值...

HTML:

<table>
  <tr>
    <td>value1</td>
    <td>value2</td>
    <td>value3</td>
  </tr>
</table>

PHP:

$html = 'http://www.example.com'; // edited

$dom = new DOMDocument;

@$dom->loadHTML($html);
$data = $dom->getElementsByTagName('tr:nth-child(3n)');

foreach ($data as $datas){
        echo $link->nodeValue;
}

使用这种或不同的方法,如何获取特定td元素的值...?

3 个答案:

答案 0 :(得分:1)

xPath可用于获取特定元素。尝试以下代码从给定的html中获取第三个td值。

$html = '<table>
  <tr>
    <td>value1</td>
    <td>value2</td>
    <td>value3</td>
  </tr>
</table>';
$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$table = $dom->getElementsByTagName('table')->item(0);
$query = 'tr/td[3]';

$entries = $xpath->query($query, $table);

echo $entries[0]->nodeValue;

了解有关DOMXpath query()

的信息

更新file_get_content的使用也很简单,您可以在$html变量中以字符串形式检索html / xml,其余过程相同:

$html = file_get_contents("path/to/file/x.html"); // target path

答案 1 :(得分:1)

使用getElementsByTagName()会根据您的起点返回标签列表,因此一旦找到该表,便可以使用相同的功能来获取<td>标签。然后,您可以随便挑选元素...

$data = "<table>
  <tr>
    <td>value1</td>
    <td>value2</td>
    <td>value3</td>
  </tr>
</table>";

$dom = new DOMDocument;

$dom->loadHTML($data);
$table = $dom->getElementsByTagName('table');
$td = $table[0]->getElementsByTagName('td'); // Fetch all td elements in the first table

echo $td[2]->nodeValue;   // Echo out the value of the 3rd item (zero based arrays)

打印出..

value3

答案 2 :(得分:-1)

我认为这应该对您有帮助。

只需为td元素分配类名,然后使用它

例如:

<td class="two">value2</td>
$(this).closest('tr').children('td.two').text();