Xpath php fetch links

后端 未结 2 460
鱼传尺愫
鱼传尺愫 2021-01-21 16:41

I\'m using this example to fetch links from a website :

http://www.merchantos.com/makebeta/php/scraping-links-with-php/

$xpath = new DOMXPath($dom);
$hre         


        
相关标签:
2条回答
  • 2021-01-21 17:17

    Try this:

    $link_title = $href->nodeValue;
    
    0 讨论(0)
  • 2021-01-21 17:34

    You are looking for the "nodeValue" of the Textnode inside the "a" node. You can get that value with

    $title = $href->firstChild->nodeValue;
    

    Full working example:

    <?php
    $dom = DomDocument::loadHTML("<html><body><a href='www.test.de'>DONE</a></body></html>");
    
    $xpath = new DOMXPath($dom);
    $hrefs = $xpath->evaluate("/html/body//a");
    
    for ($i = 0; $i < $hrefs->length; $i++) {
        $href = $hrefs->item($i);
        $url = $href->getAttribute('href');
        $title = $href->firstChild->nodeValue;
        echo "<br />Link stored: $url $title";
    }
    

    Prints:


    Link stored: www.test.de DONE

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