PHP DOM: parsing a HTML list into an array?

前端 未结 1 1026
你的背包
你的背包 2020-12-15 13:12

I have the below HTML string, and I would like to turn it into an array.

$string = \'
1


        
相关标签:
1条回答
  • 2020-12-15 13: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.

    0 讨论(0)
提交回复
热议问题