【问题标题】:Html dom parser php tablehtml dom解析器php表
【发布时间】:2015-08-25 08:51:42
【问题描述】:

这是我的桌子

Grapes    1     25     25
Mangoes   2     30     60
Apple     5     10     50

而我上表的 Html 代码是

<table>
<tr>
<td><font>Grapes</font></td>
<td><font>1</font></td>
<td><font>25</font></td>
<td><font>25</font></td>
</tr>
<tr>
<td><font>Mangoes</font></td>
<td><font>2</font></td>
<td><font>30</font></td>
<td><font>60</font></td>
</tr>
<tr>
<td><font>Apple</font></td>
<td><font>5</font></td>
<td><font>10</font></td>
<td><font>50</font></td>
</tr>
</table>

上表是我的 html 代码中的第 4 个表

我的php代码是

<?php
include('simple_html_dom.php');
$result = curl_exec($ch);
curl_close($ch);
$src = new DOMDocument('1.0', 'utf-8');
$src->formatOutput = true;
$src->preserveWhiteSpace = false;
@$src->loadHTML($result);
$xpath = new DOMXPath($src);
$values=$xpath->query('//table[4]//tr');

foreach($values as $value)
{
$rowdata = str_replace(">"," ",$value->nodeValue);
$n = explode("\n", $rowdata);
print_r($n);
}

这里 $result 保存来自 curl 执行的 html 代码

我的输出是

Array ( [0] => Grapes12525 [1] => ) Array ( [0] => Mangoes23060 [1] => ) Array ( [0] => Apple51050 [1] => )

但我想输出为

Array ( [0] => Grapes [1] => 1 [2] => 25 [3] => 25 ) Array ( [0] => Mangoes [1] => 2 [2] => 30 [3] => 60 ) Array ( [0] => Apple [1] => 5 [2] => 10 [3] => 50 )

我试过了

$values=$xpath->query('//table[4]//tr//td');

但这是将每个值打印为数组

是否有任何方法可以让我们在 for 循环中获取子元素,例如只有 td 在父 tr 中或任何其他方式来实现这一点

请帮我解决这个问题

谢谢

【问题讨论】:

标签: php html parsing dom simple-html-dom


【解决方案1】:

我会尝试:

$rowdata = explode(' ', $value->textContent);

文本内容应该是由空格分隔的tr children的整个文本。

如果这不起作用。在 foreach 循环中使用 //td$value 作为上下文节点执行另一个 xpath 查询。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-18
    • 2012-08-24
    • 1970-01-01
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多