本文介绍了PHP DOM:将HTML列表解析成数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个html列表转换成一个数组,

I want to turn the a html list into an array,

$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方法,

I am working on DOM method,

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

print_r($array);

结果,

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

但我正在寻找这样的结果,

but I am looking for the result like this actually,

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>
)

可以吗?

推荐答案

将节点传递给获取其HTML表示:

Pass the node to DOMDocument::saveHTML to get its HTML representation:

$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);

结果:

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>
)

仅适用于PHP 5.3.6及更高版本。

Only works with PHP 5.3.6 and higher, by the way.

这篇关于PHP DOM:将HTML列表解析成数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 10:02