2016-09-20 69 views
0

需要更改由SimpleHtmlDom生成的数组格式的输出。我的PHP代码是。我使用的SimpleHtmlDom的结果是返回医院名称作为关键不是值?:使用SimpleHtmlDom的数组格式

<?php 
require('simple_html_dom.php'); 

$table = array(); 
$html = file_get_html('https://www.miemssalert.com/chats/Default.aspx?hdRegion=3'); 

foreach($html->find('table#tblHospitals tr td.Chats') as $e) 
{ 
    //echo $e->plaintext . $e->getAttribute('style') . '<hr>'; 
$nametime = $e->plaintext; 
$color = $e->getAttribute('style'); 
$table[$nametime][$color] = true; 
} 
echo json_encode($table); 

echo '<pre>'; 
    var_dump($table); 
echo '</pre>'; 
?> 

当前阵列结果:

array(37) { 
    ["Anne Arundel Medical Center"]=> 
    array(1) { 
    [0]=> 
    bool(true) 
    } 
    [""]=> 
    array(1) { 
    [0]=> 
    bool(true) 
    } 
    ["Baltimore Washington Medical Center"]=> 
    array(1) { 
    [0]=> 
    bool(true) 
    } 
    ["04:31"]=> 
    array(1) { 
    ["background-color:#ffff00;color:#000000;"]=> 
    bool(true) 
    } 
    ["Bon Secours Hospital"]=> 
    array(1) { 
    [0]=> 
    bool(true) 
    } 
... 

寻找结果的名称被嵌套阵列= >时间=>颜色

array(37) { 
    array(1) {["Name"]=>["Anne Arundel Medical Center"]=> 
    array(2) { 
    [time]=>[""],[color]=>[""] 
    } 
    } 
    array(1) {["Name"]=>["Baltimore Washington Medical Center"]=> 
    array(2) { 
    [time]=>["04:31"],[color]=>["background-color:#ffff00;color:#000000;"] 
    } 
    } 
    array(1) {["Name"]=>["Bon Secours Hospital"]=> 
    array(2) { 
    [time]=>[""],[color]=>[""] 
    } 
    } 
... 
+0

您应该遍历'tr'元素,而不是'td.Chats'。 tr中的第一个'td'成为名字。然后遍历行中剩余的“td”元素以获取时间和颜色。 – Barmar

+0

为什么你有'数组(1)'有两个元素,'时间'和'颜色'的数组。 – Barmar

+0

已更正的问题,如果没有时间,结果将为空白,请参阅新更改 - 另请参阅有关此主题的原始文章:http://stackoverflow.com/questions/39574672/screen-scraping-php-using-simplehtmldom – BarclayVision

回答

1

您需要遍历行而不是单元格,以便每个医院对应结果数组中的元素。从该行中的第一个td获取医院名称,并从嵌套循环中获取剩余部分的时间和颜色。

<?php 
require('simple_html_dom.php'); 

$table = array(); 
$html = file_get_html('https://www.miemssalert.com/chats/Default.aspx?hdRegion=3'); 

foreach($html->find('table#tblHospitals tr') as $hosp) 
    { 
     $tds = $hosp->find('td.Chats'); 
     if (!empty($tds)) { 
      $name = $tds[0]->plaintext; 
      $row = array('name' => $name, 'time' => array(), 'color' => array()); 
      foreach (array_slice($tds, 1) as $e) { 
       $time = $e->plaintext; 
       $color = $e->getAttribute('style'); 
       $row['time'][] = $time; 
       $row['color'][] = $color; 
      } 
      $table[] = $row; 
     } 
    } 

echo '<pre>'; 
var_dump($table); 
echo '</pre>'; 
+0

这是给所有空值? – BarclayVision

+0

我有一些错误。我也没有跳过标题行。 – Barmar

+0

工作很好,非常感谢,我不知道如何用SimpleHtmlDom来完成此任务 - 非常感谢! – BarclayVision