我如何在foreach循环PHP中使用array_push?

时间:2012-03-28 05:39:16

标签: php foreach array-push

这是我尝试的例子

<?php
 include 'spider/classes/simple_html_dom.php';
 $html = new simple_html_dom();
 $html->load("<html><body><h2>Heading 1</h2><h2>This heading 2</h2></p></p></body></html>");
 $e = $html->find("h2", 0);
 $key = array();
 if($e->plaintext != ""){
 foreach($html->find("h2", 0) as $e){
    //echo $e->plaintext;
    array_push($key, $e->plaintext);
  }
 } else {
     echo "error";
 }
 print_r($key);
 ?>

结果:
数组([0] =&gt; [1] =&gt; [2] =&gt; [3] =&gt; [4] =&gt; [5] =&gt;标题1此标题2

[6] =&gt; [7] =&gt; )

如何使用array_push创建数组?

2 个答案:

答案 0 :(得分:2)

当您尝试此代码时会发生什么? 我删除了第一个“查找”,我也在互联网上找到了一个例子,其中第二个“查找”参数未设置。

<?php
 include 'spider/classes/simple_html_dom.php';
 $html = new simple_html_dom();
 $html->load("<html><body><h2>Heading 1</h2><h2>This heading 2</h2></p></p></body></html>");
 $key = array();
 if(isset($html)){
 foreach($html->find("h2") as $e){
    //echo $e->plaintext;
    array_push($key, $e->plaintext);
  }
 } else {
     echo "error";
 }
 print_r($key);
 ?>

说明:

// Find all anchors, returns a array of element objects
$ret = $html->find('a');

// Find (N)th anchor, returns element object or null if not found (zero based)
$ret = $html->find('a', 0);

答案 1 :(得分:0)

这是使用默认 DOMDocument 类的替代方法。

$html = new DOMDocument('1.0','utf-8');
$html->loadHTML("<html><body><h2>Heading 1</h2><h2>This heading 2</h2></p></p></body></html>");

$key = array();
$h2 = $html->getElementsByTagName('h2');

for ($i = 0; $i < $h2->length; $i++) {
    array_push($key, $h2->item($i)->nodeValue);
}
print_r($key);
相关问题