How to get a div via PHP?

前端 未结 3 2019
没有蜡笔的小新
没有蜡笔的小新 2021-02-06 17:14

I get a page using file_get_contents from a remote server, but I want to filter that page and get a DIV from it that has class \"text\" using PHP. I started with

3条回答
  •  我寻月下人不归
    2021-02-06 18:05

    Once you have loaded the document to a DOMDocument instance, you can use XPath queries on it -- which might be easier than going yourself through the DOM.

    For that, you can use the DOMXpath class.


    For example, you should be able to do something like this :

    $dom = new DOMDocument();
    $dom->loadHTML($html);
    
    $xpath = new DOMXPath($dom);
    $tags = $xpath->query('//div[@class="text"]');
    foreach ($tags as $tag) {
        var_dump($tag->textContent);
    }
    


    (Not tested, so you might need to adapt the XPath query a bit...)

提交回复
热议问题