2012-03-28 5 views
1

私はforeachループPHPで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] => [1] => [2] => [3] => [4] => [ 5] => 2

[6] => [7] =>)

私は配列を作成するためにarray_push使用していますどのように

を見出し1この見出し?

答えて

2

このコードを試してみるとどうなりますか? 私は最初の "find"を削除しました。また、 "find"の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); 
+0

うんうんうまんしています。どうもありがとうございます.. –

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); 
関連する問題