简体   繁体   English

XPath选择TD内的TD

[英]XPath select TD's inside TR

I want to capture all the content between td tags but divide them by their tr. 我想捕获td标签之间的所有内容,但将它们除以tr。 So i can get an array with the content inside every tr. 这样我就可以得到一个数组,其中包含每个tr中的内容。

<div id="box">
<tr align='center'>
<td>1</td>
<td style='padding-left: 0px !important;padding-right: 10px !important;'>   <div id=''></div></td> 
<td>45</td>
<td>62</td>
</tr><tr align='center'>
<td>2</td>
<td style='padding-left: 0px !important;padding-right: 10px !important;'>   <div id=''></div></td> 
<td>35</td>
<td>47</td>
</tr><tr align='center'>
<td>3</td>
<td style='padding-left: 0px !important;padding-right: 10px !important;'>   <div id=''></div></td> 
<td>63</td>
<td>58</td>
</tr>

I've tried with this: 我已经试过了:

<?php
$url = '';
$html = file_get_contents($url);
$doc = new DOMDocument();
$doc->preserveWhiteSpace = FALSE;
@$doc->loadHTML($html);
$xpath = new DOMXpath ($doc);
$expresion = "//div[@id='box']//tr//td";
$node = $xpath->evaluate($expresion);
foreach ($node as $nd)
{
echo $nd->nodeValue;
}
?>

But the output is: 但是输出是:

1

45
62
2

35
47
3

63
58

If you want to group the td values by their tr , I would separate the xpath into two queries. 如果要将td值按其tr分组,我将xpath分为两个查询。 One query selects the <tr> nodes and a second query selects the <td> childs of that node. 一个查询选择<tr>节点,第二个查询选择该节点的<td>节点。

If you put that into a loop it can look like this: 如果将其放入循环中,则可能如下所示:

<?php

$html = <<<EOF
<div id="box">

    ... Your HTML comes here
</tr>
EOF;

$url = '';
$doc = new DOMDocument();
$doc->preserveWhiteSpace = FALSE;
@$doc->loadHTML($html);
$xpath = new DOMXpath ($doc);
$expresion = "//div[@id='box']//tr";
$trs = $xpath->evaluate($expresion);
foreach ($trs as $tr)
{
    $tdvals = array();
    foreach($xpath->query('td', $tr) as $td) {
        /* Skip the td with the empty text value */
        if(trim($td->nodeValue) !== '') {
            $tdvals []= $td->nodeValue;
        }
    }
    echo implode(',', $tdvals) . PHP_EOL;
}

which outputs: 输出:

1,45,62
2,35,47
3,63,58

One another thing. 另一件事。 In your example you are using file_get_contents() to load the HTML. 在您的示例中,您正在使用file_get_contents()加载HTML。 Note that you can use DOMDocument::loadHTMLFile() to load (remote) files. 请注意,您可以使用DOMDocument::loadHTMLFile()加载(远程)文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM