dpowhyh70416 2012-04-28 18:42
浏览 69
已采纳

PHP DOM:将HTML列表解析为数组?

I have the below HTML string, and I would like to turn it 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>
';

Here's my current code with DOMDocument:

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

print_r($array);

However, this gives the below output:

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

But I am looking for this result:

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

Is this possible?

  • 写回答

1条回答 默认 最新

  • drxv39706 2012-04-28 18:45
    关注

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

    Result:

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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画