gpt4 book ai didi

PHP DOM : parsing a HTML list into an array?

转载 作者:可可西里 更新时间:2023-11-01 13:35:24 25 4
gpt4 key购买 nike

我有下面的 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>
';

这是我当前使用 DOMDocument 的代码:

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

但我正在寻找这个结果:

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

这可能吗?

最佳答案

将节点传递给DOMDocument::saveHTML获取其 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);

结果:

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 及更高版本。

关于PHP DOM : parsing a HTML list into an array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10366458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com