0

我怎样才能使这个解析器更有效率?我觉得这些 if 语句很疯狂!我认为回调函数将能够完成工作。但是,我的大多数标识符都大相径庭,我需要通过许多不同的键。我应该创建一个标签数组和一个 DOM 元素数组,并为每个元素创建一个回调函数以去除空值吗?我第一次尝试组装一个刮板,我真的被这里的逻辑难住了。

任何帮助将不胜感激!

foreach($html->find('.b-card') as $article) {
    $data[$y]['business']     = $article->find('h1', 0)->plaintext;
    $data[$y]['address']      = $article->find('.address', 0)->plaintext;

    if($article->find('.phone-num', 0)) {
      $data[$y]['phone']      = $article->find('.phone-num', 0)->plaintext;
    } else {
       $data[$y]['phone']     = 'Number not listed.';
    }

    if($article->find('.link', 0)) {
      $data[$y]['website']    = $article->find('.link', 0)->plaintext;
    } else {
       $data[$y]['website']   = 'Website not listed.';
    }
    if($article->find('.established', 0)) {
      $data[$y]['years']    = str_replace("\r\n","",$article->find('.established', 0)->plaintext);
    } else {
       $data[$y]['years']   = 'Years established not listed.';
    }
    if($article->find('.open-hours', 0)) {
      $data[$y]['hours']    = $article->find('.open-hours', 0)->plaintext;
    } else {
       $data[$y]['hours']   = 'Hours not listed.';
    }
    if($article->find('.categories a', 0)) {
      $data[$y]['category']    = $article->find('.categories a', 0)->plaintext;
    } else {
       $data[$y]['category']   = 'Category not listed.';
    }

    $articles[] = $data[$y];
}

}

我觉得我可以做这样的事情

function my_callback($element) {
        // remove all null tags 
        if ($element->tag)
                $article->find....;
} 
4

1 回答 1

0

if使用一个数组来收集每个块中的所有相关信息。

$selector_list = array(
    array('selector' => '.phone-num', 'index' => 'phone', 'name' => 'Number'),
    array('selector' => '.link', 'index'' => 'website', 'name' => 'Website'),
    array('selector' => 'open-hours', 'index' => 'hours', 'name' => 'Hours'),
    array('selector' => '.categories a', 'index' => 'category', 'name' => 'Category')
);

然后,您可以使用包含所有常见代码的简单foreach循环:

foreach ($selector_list as $sel) {
    $found = $article->find($sel['selector'], 0);
    if ($found) {
        $data[$y][$sel['index']] = $found;
    } else {
        $data[$y][$sel['index']] = $sel['name'] . " not listed.";
    }
}
// Special case for selector that doesn't follow the same pattern
$found = $article->find('.established', 0);
if ($found) {
    $data[$y]['years'] = str_replace("\r\n", "", $found);
} else {
    $data[$y]['years'] = Years established not listed.';
}

如果您希望循环能够处理需要特殊处理的循环,您可以向数组添加一个回调函数。但如果这只是一个奇怪的案例,那可能是矫枉过正。

于 2017-09-09T05:00:15.510 回答