1

I have some HTML that is setup like the following (this can be different though!):

<table></table>
<h4>Content</h4>
<table></table>

I'm using PHP Simple HTML DOM Parser to loop over a section of code setup like this:

enter image description here

How can I say something like - "Find the table and the preceding h4, grab the text from the h4 if it exists, if it doesn't then leave blank".

If I just use $html->find('div[class=product-table] h4'); then it ignores the fact there was no title for the first table.

This is my full code for context:

$table_rows = $html->find('div[class=product-table] table');
$tablecounter = 1;
foreach ($table_rows as $table){
  $tablevalue[] =
    array(
        "field_5b3f40cae191b"   => "Table",
    );
}
update_field( $field_key, $tablevalue, $post_id );

Update:

I've found in the documentation that you can use prev_sibling() so I've tried $table_title = $html->find('div[class=product-table] table')->prev_sibling('h4'); but can't seem to get it to work.

1
  • maybe you can search for "</table><h4>" might be easier if your code is uniform. Commented Jul 9, 2018 at 15:08

1 Answer 1

1

I've simplified the example to hopefully show the situation your after, it does assume that the <h4> tag is immediately prior to the <table> tag. But it uses the prev_sibling() of the table tag you find.

require_once 'simple_html_dom.php';
$source = "<html>
<body>
    <div class='product-table'>
        <table>t1</table>
        <h4>Content</h4>
        <table>t2</table>
    </div>
</body>
</html>";

$html = str_get_html($source);
$table_rows = $html->find('div[class=product-table] table');
foreach ($table_rows as $table){
    $prev = $table->prev_sibling();
    if ( !empty($prev) && $prev->tag == "h4")   {
        echo "h4=".(string)$prev->innertext().PHP_EOL;
    }
    echo "content=".(string)$table.PHP_EOL;
}

echos..

content=<table>t1</table>
h4=Content
content=<table>t2</table>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.