PHP Simple HTML DOM Parser finding specific text

2019-06-11 22:21发布

Trying to get data from this poorly created HTML format

http://www.weather.gov.sg/lws/zoneInfo.do

All I need is to get data for 3 places, e.g. Bedok, City and Katong. How do I store the data in an array for this?

This is what I did to get the store the first 5 lines, which is not exactly what I want.

$row_counter='0';
while($row_counter<5)
{
$ret['Name'][] = $html->find('.FORM1', $row_counter)->innertext;
$ret['Area'][] = $html->find('.FORM1', $row_counter)->next_sibling()->innertext;
$ret['Alert'][] = $html->find('.FORM1', $row_counter)->next_sibling()->next_sibling()->innertext;
$ret['From'][] = $html->find('.FORM1', $row_counter)->next_sibling()->next_sibling()->next_sibling()->innertext;
$ret['Till'][] = $html->find('.FORM1', $row_counter)->next_sibling()->next_sibling()->next_sibling()->next_sibling()->innertext;
$row_counter++;
}

I am able to store data successfully for the whole row and all columns. What is the most efficient way to search for a certain name, e.g. Bedok and getting the columns beside it like next_sibling?

Thanks.

1条回答
三岁会撩人
2楼-- · 2019-06-11 22:31

Isn't it easy. Try things first then ask. (:

<?php
include 'simple_html_dom.php';
$html = file_get_html('http://www.weather.gov.sg/lws/zoneInfo.do');

$n = 0;
$table = $html->find('table',3)->find('table',0)->find('table',0)->find('table',0)->find('table',3)->find('table',0);

$i = -3;
$rows = $table->find('tr');
$holder = array();

foreach($rows as $element){
    $i++;
    if($i < 0) continue;

    $holder[$i]['name'] = $element->find('td',0)->plaintext;
    $holder[$i]['zone_or_school'] = $element->find('td',1)->plaintext;
    $holder[$i]['risk'] = $element->find('td',2)->plaintext;
    $holder[$i]['from'] = $element->find('td',3)->plaintext;
    $holder[$i]['till'] = $element->find('td',4)->plaintext;
}

var_dump($holder);
?>

if you want to get a particular data then you can filter it out:

foreach($holder as $key => $val)
{
if($holder[$key]['name']=='Bedoc')
$my_data = $holder[$key];
}

this code isn't debuged cause i am on mobile now. But maybe you have get the idea if not works. Thanks

查看更多
登录 后发表回答