Grow your CSS skills. Land your dream job.

PHP Simple HTML DOM Parser [HELP]

  • # November 6, 2012 at 1:00 pm

    Hey,

    I am working on an app in which I am using [PHP Simple HTML DOM Parser](http://simplehtmldom.sourceforge.net/ “”). Now what is I have for example following HTML which I have fetched in sting:

    <table>
    <tbody>
    <tr>
    <th>Column1</th>
    <th>Column2</th>
    <th>Column3</th>
    </tr>
    <tr>
    <td><a href=”#”>First Link</a></td>
    <td>Some content here
    <td><a href=”#”>Another Link</a></td>
    </tr>
    <tr>
    <td><a href=”#”>First Link</a></td>
    <td>Some content here
    <td><a href=”#”>Another Link</a></td>
    </tr>
    </tbody>
    </table>

    Now what I want is to fetch first link of every element and echo it’s src on screen.

    __
    # November 6, 2012 at 10:08 pm

    …I’m assuming that <table> is the HTML in question?

    (You can post HTML in your comments by writing `<` in place of `< `.)

    > what I want is to fetch first link of every
    element

    Do you mean “links in the first column”?

    I’ve never used this class, but according to the page you linked to, it would be as simple as loading the HTML string and using the `find()` method:

    // find each table row
    foreach( $HTMLstring->find( ‘tr’ ) as $tr ){
    // find the first column in each row
    foreach( $tr->find( ‘td’,0 ) ){
    // if there is an anchor
    if( ($a = $td->find( ‘a’,0 ) ) ){
    // if the anchor is a hyperlink, print the href
    if( isset( $a->href ) ){ print $a->href; }
    }
    }
    }

    Have you tried anything like this? If you need help, post the code you’ve tried so far and describe what problems you’ve encountered.

    # November 7, 2012 at 2:30 am

    I have tried this kind of code including this one which you posted but it is showing:

    > Invalid argument supplied for foreach()

    as what I understand that when we are finding first occurrence of we can’t make it in loop.

    __
    # November 7, 2012 at 10:16 am

    That means that the parser didn’t find any matching elements:

    > …returns element object or **null if not found**.

    > *[emphasis added]*

    You can check like so:

    if( ($html = $HTMLstring->find( ‘tr’ )) !== null ){
    foreach // . . .etc.

    If you’d like more help, post your code.

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".