[英]How can I make this PHP DOM parser more efficient with nested arrays?
如何使此解析器更高效? 我觉得这些语句很疯狂! 我在想,一个回调函数将能够完成这项工作。 但是,我的大多数标识符都大相径庭,我需要使用许多不同的密钥。 我应该制作一个标记数组和一个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....;
}
使用一个数组收集每个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.';
}
如果希望循环能够处理需要特殊处理的循环,则可以向数组添加回调函数。 但是,如果这只是一个奇怪的案例,那可能就太过分了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.