php:如何将scped html分配给数组

时间:2016-07-07 00:16:07

标签: php xpath domdocument domxpath

我想格式化以下php脚本输出的内容:

 <?php

$stop = $_POST["stop_number"];  // stop_number is an text input value provided by user
$depart_url = "http://64.28.34.43/hiwire?.a=iNextBusResults&StopId=" . $stop;
$html = file_get_contents($depart_url);
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);

$my_xpath_query = "//td[@valign='top']";
$result = $xpath->query($my_xpath_query);

foreach($result as $result_object)
{
    echo $result_object->childNodes->item(0)->nodeValue,'<br>';
}

?>

这是输出(至少在一个实例中,随着时间的推移,数据会发生变化)。

18 - GOLD
OUTBOUND
8:17p
8:16p
8 - GREEN 
OUTBOUND
8:46p
8:46p
8 - GREEN 
OUTBOUND
18 - GOLD
OUTBOUND
5 - PLUM
OUTBOUND

编辑:

我希望上面的输出信息放在如下表中。但是,不是标签之间的文本,而是来自php脚本输出的变量或项目。

<!DOCTYPE html>
<html>
<title>Departure Table</title>

<body>
<h4>Next Departures for Stop Number: __ </h4>
<table border="1px solid black">
    <tr>
        <th>Route</th>
        <th>Direction</th>
        <th>Scheduled</th>
        <th>Estimated</th>
    </tr>
    <tr>
        <td>18 - Gold</td>
        <td>Outbound</td>
        <td>8:17p</td>
        <td>8:16p</td>
    </tr>
    <tr>
        <td>8 - Green</td>
        <td>Outbound</td>
        <td>8:46p</td>
        <td>8:46p</td>
    </tr>
</table>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

尝试在echo语句后添加\ n标记:

    echo $result_object->childNodes->item(0)->nodeValue."\n";

编辑:

如果要将数据存储在PHP变量中,可以执行以下操作:

将数据存储在数组中,如变量(或根据您的需要的任何其他数据结构),并迭代变量。

$store_data_in_array_variable = array();

foreach($result as $result_object)
{
    $store_data_in_array_variable[] = $result_object->childNodes->item(0)->nodeValue;

}

//iterate over all stored values

foreach ($store_data_in_array_variable as $key => $value) 
{
    echo $key;
    echo '<br>';
    echo $value;
}