doxp30826
doxp30826
采纳率0%
2018-01-21 23:51

具有多个表的PHP简单HTML DOM解析器

已采纳

I am trying to parse html data from a local weather channels site to get closing informations for schools, businesses, and churches around my local area.

I have run into the problem though that the information is contained in tables that do not have an id that I can use to identify them. Below I have included an example of what one of their html tables looks like. Is it possible to parse multiple HTML tables like this and pull the containing data using HTML DOM Parser with PHP. I have read through this documentation, but can't seem to find an applicable solution.

Thanks!

EDIT: I should probably also specify I want to take this data and be able to parse it to JSON data to use to load in an application. So basically have the organizations name and then the status that I can fetch from a JSON page.

Link to weather channels site

<table class="table table-condensed table-striped">
  <tbody>
    <tr>
      <th class="span5">Organization</th>
      <th class="span9">Status</th>
    </tr>
    <tr>
      <td><b>BEACON HOPE CHURCH - GRAND ISLAND</b></td>
      <td>Activity Canceled Sunday<small>: No Evening Classes</small></td>
    </tr>
    <tr>
      <td><b>PRINCE OF PEACE CATHOLIC (KEARNEY)</b></td>
      <td>Closed Monday<small>: SUNDAY EVENING ACTIVITIES CANCELED, NO MON. MORNING MASS, OFFICES CLOSED MON.</small></td>
    </tr>
  </tbody>
</table>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dongleibeng5602 dongleibeng5602 3年前

    Found the answer to my question with help from user sms who commented above. This php pulls the data from the first table and encodes it in the JSON format.

    <?php
    
    include('simple_html_dom.php');
    header('Content-Type: application/json');
    
    $html = file_get_html('http://www.1011now.com/weather/closings');
    $row_count=0;
    $json = array();
    
    // Find all links 
    $table = $html->find('table', 0);
    foreach($table->find('tr') as $row) {
        $name = $row->find('td',0)->innertext;
        $status = $row->find('td',1)->innertext;
    
        $json[] = [ 'name' => strip_tags($name), 'status' => strip_tags($status)];
    }
    
    $options = array(
        'http' => array(
        'method'  => 'POST',
        'content' => json_encode(array('Closings' =>$json)),
        'header'=>  "Content-Type: application/json
    " .
                    "Accept: application/json
    "
        )
    );
    
    $context  = stream_context_create( $options );
    $result = file_get_contents( $url, false, $context );
    $response = json_decode( $result );
    
    echo json_encode(array('Closings' =>$json), JSON_PRETTY_PRINT);  
    
    
    ?>
    
    点赞 评论 复制链接分享