2012-04-28 19 views
5

Chcę włączyć listę HTML do tablicy,PHP DOM: parsowanie listy HTML do tablicy?

$string = ' 
<a href="#" class="something">1</a> 
<a href="#" class="something">2</a> 
<a href="#" class="something">3</a> 
<a href="#" class="something">4</a> 
'; 

pracuję nad metodą DOM,

$dom = new DOMDocument; 
$dom->loadHTML($string); 
foreach($dom->getElementsByTagName('a') as $node) 
{ 
    $array[] = $node->nodeValue; 
} 

print_r($array); 

wynik,

Array ([0] => 1 [1] => 2 [2] => 2 [3] => 4) 

ale szukam dla taki wynik faktycznie istnieje,

Array ( 
[0] => <a href="#" class="something">1</a> 
[1] => <a href="#" class="something">2</a> 
[2] => <a href="#" class="something">3</a> 
[3] => <a href="#" class="something">4</a> 
) 

czy to możliwe?

Odpowiedz

19

Przełóż węzeł DOMDocument::saveHTML dostać swoją reprezentację HTML:

$string = ' 
<a href="#" class="something">1</a> 
<a href="#" class="something">2</a> 
<a href="#" class="something">3</a> 
<a href="#" class="something">4</a> 
'; 

$dom = new DOMDocument; 
$dom->loadHTML($string); 
foreach($dom->getElementsByTagName('a') as $node) 
{ 
    $array[] = $dom->saveHTML($node); 
} 

print_r($array); 

Wynik:

Array 
(
    [0] => <a href="#" class="something">1</a> 
    [1] => <a href="#" class="something">2</a> 
    [2] => <a href="#" class="something">3</a> 
    [3] => <a href="#" class="something">4</a> 
) 

Działa tylko z PHP 5.3.6 i wyższe, tak przy okazji.

+0

Dziękuję bardzo za odpowiedź! – laukok

+0

niezły, nie wiedziałem o nowym parametrze węzła. – goat