Search code examples
phphtmlurldomhref

Get attribute based on simple HTML DOM


How to get the contents of an href attribute on an HTML page, based on simple HTML DOM. Here is an example of my script:

<?php
/* update your path accordingly */
include_once 'simple_html_dom.php';

$url = "http://www.codesphp.com/";
$html = file_get_html($url);
$ret =  $html->find('span.titleSnnipets');



foreach($ret as $story){
    echo $story->find('a',0).'<br/>';
}
?>

this script retrieve all tags on the page,i try to retrieve the contents of the attribute of all links.


Solution

  • Since we can't see the content of your localhost, it is difficult to help you with. I only saw one small thing that I know could be optimized, and that is the first find() call.

    <?php
    include_once 'simple_html_dom.php';
    
    $url = "http://localhost/website/";
    $html = file_get_html($url);
    $ret =  $html->find('span.title');
    
    foreach($ret as $story)
    {
        echo $story->find('a',0).'<br/>';
    }
    ?>
    

    Update: I already said, since I can't see the content you are using, it is difficult to help you. Your response is to just ask for help again, but make no effort to provide the content? Since you refuse to make your content accessible, I have rewritten your code to use google instead. This example works as expected. Take it and modify it as you need. Until you provide your content, I cannot help you any further.

    <?php
    include_once 'simple_html_dom.php';
    $html = file_get_html('http://www.google.com/');
    $divs = $html->find('div.gbm');
    foreach($divs as $element)
    {
        echo $element->find('a', 0).'<br>';
    }
    ?>
    

    Update #2: This will pull all of the links on the page and display them.

    <?php
    include_once 'simple_html_dom.php';
    $html = file_get_html('http://www.codesphp.com/');
    $links = $html->find('a');
    foreach($links as $link)
    {
        echo $link->href.'<br>';
    }
    ?>