首页 > 解决方案 > 我如何在不重复自己的情况下更好地编写此语句,它需要使用简单的 html dom 的值

问题描述

我有这个块代码,它工作正常,但我觉得我重复了很多次,当它们回来时它会减慢结果。我正在使用简单的 html dom 来获得结果。我怎样才能尽可能有效地做到这一点?

$html = file_get_html( $urlfix );

// now lets go through all results to see what we get

$links = array();
foreach ( $html->find( 'div.mozaique div.thumb-block ' ) as $a ) {
    $links[] = $a->id;
}

// this will return  images

$datasrc = 'data-src';
$links2 = array();
foreach ( $html->find( 'div.mozaique div.thumb-block img ' ) as $a ) {
    $links2[] = $a->$datasrc;
}

// this will return the links


$links3 = array();
foreach ( $html->find( 'div.mozaique div.thumb-block div.thumb a ' ) as $a ) {
    $links3[] = $a->href;
}

// print_r($links3);

$links4 = array();
foreach ( $html->find( 'div.mozaique div.thumb-under p.title a ' ) as $a ) {
    $links4[] = $a->title;
}

// this will return another set of links

$vidoid = 'data-id';

$links5 = array();
foreach ( $html->find( 'div.mozaique div.thumb-block  ' ) as $a ) {
    $links5[] = $a->$vidoid;
}

标签: phpforeachsimple-html-dom

解决方案


使它成为一个函数并多次调用它。

例如:

function get_list($html, $find, $element) {
    $list = array();
    foreach ( $html->find($find) as $a ) {
        $list[] = $a->$element;
    }
    return $list;
}

$links = get_list($html, 'div.mozaique div.thumb-block ', 'id');

推荐阅读