php - 我如何在不重复自己的情况下更好地编写此语句,它需要使用简单的 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;
}
解决方案
使它成为一个函数并多次调用它。
例如:
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');
推荐阅读
- r - 将不同的游戏平滑回归 (mgcv) 与 ggally [R] 配对
- jquery - 我需要帮助在 shopify 中定位 datepicker
- python - 如何为“open”编写满足 Pylint 考虑使用的上下文管理器包装器
- variables - 在 Redshift 返回错误的存储过程中传递变量
- databricks - 在没有任何数据的情况下读取增量位置时出现“无事务日志”错误
- python - 如果调用 showGrid,pyqtgraph 会切断刻度标签
- python - 无法在托管服务器上运行 Python
- postgresql - 如何在不使用自制软件的情况下在终端上启动 postgresql?(SQL 状态:42501,尝试使用 COPY 将 CSV 导入 pgAdmin4)
- javascript - Laravel 将数据从视图发送到 JavaScript 文件
- html - 如何缩进 ul > li 结构中的每个同级?