php : how to write $item$i


php : how to write $item$i

如何正确编写?

for($i=2;$i<5;$i++)
{
   $items{$i} = $doc{$i}->getElementsByTagName('url'); 
}

出现错误:

致命错误:在非对象上调用成员函数 getElementsByTagName()

谢谢再见

试试:

$ndoc = 'doc'. $i;
$items[$i] = $$ndoc->getElementsByTagName('url'); 

或:

$ndoc = 'doc'. $i;
$items[$i] = ${$ndoc}->getElementsByTagName('url'); 

这个测试对我有用:-

$html1 = "<html><head><title>Test</title></head><body><p>Doc1 P1</p><p>Doc1 P2</p></body></html>";
$html2 = "<html><head><title>Test</title></head><body><p>Doc2 P1</p><p>Doc2 P2</p></body></html>";
$doc1 = new DOMDocument();
$doc1->loadHTML($html1);
$doc2 = new DOMDocument();
$doc2->loadHTML($html2);
for($i=1;$i<3;$i++){
    var_dump(${'doc'.$i}->getElementsByTagName('p'));
}

因此,您的代码应如下所示:-

for($i=2;$i<5;$i++)
{
   ${'items'.$i} = ${'doc'.$i}->getElementsByTagName('url'); 
}

除非您的意思是$items是一个数组,否则它应该如下所示:

for($i=2;$i<5;$i++)
{
   $items[] = ${'doc'.$i}->getElementsByTagName('url'); 
}