[英]PHP Simple HTML DOM Parser
為什么不能使用帶有變量的Class的遍歷方法來設置參數
例如,使用此數組:
array(0 => array('element' => 'img[src=images/more.gif]', 'attribute' => 'parent()->href'));
這有效:
foreach($this->contents->find($target[$key]['element']) as $keyz => $found)
{
$this->store[$keyz] = $found->parent()->href
}
但這不是:
foreach($this->contents->find($target[$key]['element']) as $keyz => $found)
{
$this->store[$keyz] = $found->$target[$key]['attribute'];
}
我試圖像這樣更改它們的數組:
array(0 => array('element' => 'img[src=images/more.gif]', 'traverse' => 'parent()', 'attribute' => 'href')
然后嘗試:
foreach($this->contents->find($target[$key]['element']) as $keyz => $found)
{
$this->store[$keyz] = $found->$target[$key]['traverse']->$target[$key]['attribute'];
}
不起作用。
在這兩次失敗中,print_r($ this-> store)都只給出Array();。
它與緩慢的簡單HTML無關,它與PHP無關:PHP不是這樣工作的,您的字符串parent()->href
不會被解釋為對這些元素的調用。 如果需要,您將走上正確的道路,但必須區分功能和屬性。 像這樣的任何一種:
array(
'element' => 'img[src=images/more.gif]',
'traverse' => array(
array('parent','function'),
array('attribute' ,'property');
...
$result = $found
foreach($target[$key]['traverse'] as $step){
switch($step[1]){
case 'function':
$function = $step[0];
$result = $found->$function();
break;
case 'property':
$property = $step[0];
$result = $found->$property;
break;
default:
trigger_error("Unknown step method ".$step[1].": not an property or function",E_USER_ERROR);
}
}
$this->store[$keyz] = $result;
或者這可以與您的原始字符串一起使用:
array(
'element' => 'img[src=images/more.gif]',
'attribute' => 'parent()->href'));
...
$result = $found;
foreach(explode('->',$target[$key]['attribute']) as $step){
if(substr($step,-2) == '()'){
$function = substr($step,0, strlen($step)-2);
$result = $result->$function();
} else {
$result = $result->$step;
}
}
$this->store[$keyz] = $result;
謝謝Wrikken,根據您的建議,我提出了這一建議,該方法非常有效
foreach($this->contents->find($target[$key]['element']) as $keyz => $found)
{
if (!isset($target[$key]['traverse']) && !isset($target[$key]['attribute']))
{
$this->store[] = $found;
}
else if (isset($target[$key]['traverse']) && !isset($target[$key]['attribute'])
{
$function = $target[$key]['traverse'];
$this->store[] = $found->$function();
}
else if (isset($target[$key]['traverse']) && isset($target[$key]['attribute']))
{
$function = $target[$key]['traverse'];
$this->store[] = $found->$function()->$target[$key]['attribute'];
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.