如何使此解析器更高效?我觉得这些陈述是疯狂的!我认为回调函数能够完成工作。 但是,我的大多数标识符都大不相同,我需要经历许多不同的密钥。我应该创建一个标签数组和一个DOM元素数组,并为每个元素创建一个回调函数来去除空值?我是第一次尝试拼凑刮刀,而且我真的被这里的逻辑所困扰。
任何帮助都会受到重视!
cout << "Enter your name: ";
cin >> MyClass.setName();
cout << "\nHello, " << MyClass.getName();
// although this isn't exactly how it'll be used in-program
我觉得我可以做这样的事情
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];
}
}
答案 0 :(得分: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.';
}
如果您希望循环能够处理需要特殊处理的循环,您可以向数组添加回调函数。但如果它只是一个奇怪的情况,那可能是矫枉过正的。