【问题标题】:How can I make this PHP DOM parser more efficient with nested arrays?如何使用嵌套数组使这个 PHP DOM 解析器更高效?
【发布时间】:2018-02-18 00:02:03
【问题描述】:

如何让这个解析器更高效?我觉得这些 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....;
} 

【问题讨论】:

    标签: php arrays simpledom


    【解决方案1】:

    使用一个数组来收集每个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.';
    }
    

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

    【讨论】:

      猜你喜欢
      • 2015-09-28
      • 1970-01-01
      • 2010-10-31
      • 1970-01-01
      • 1970-01-01
      • 2015-09-30
      • 2012-10-17
      • 1970-01-01
      • 2012-08-24
      相关资源
      最近更新 更多