PHP Dom not retrieving element

前端 未结 4 429
旧时难觅i
旧时难觅i 2021-01-14 23:45
$code = \'

Galeria

4条回答
  •  南笙
    南笙 (楼主)
    2021-01-15 00:21

    It seems that the DOMDocument will not play nice with HTML fragments. You may want to either consider the DOMDocumentFragment (as dnagirl suggests) or consider extending the DOMDocument.

    After a little research, I've put together a simple extension that will achieve what you are asking:

    class MyDOMDocument extends DOMDocument {
    
        function getElementById($id) {
    
            //thanks to: http://www.php.net/manual/en/domdocument.getelementbyid.php#96500
            $xpath = new DOMXPath($this);
            return $xpath->query("//*[@id='$id']")->item(0);
        }
    
        function output() {
    
            // thanks to: http://www.php.net/manual/en/domdocument.savehtml.php#85165
            $output = preg_replace('/^/', '',
                    str_replace( array('', '', '', ''),
                            array('', '', '', ''), $this->saveHTML()));
    
            return trim($output);
    
        }
    
    }
    

    Usage

    $dom = new MyDOMDocument();
    $dom->loadHTML($code);
    
    var_dump($dom->getElementById("galeria_list"));
    
    echo $dom->output();
    

提交回复
热议问题