0

Hello I've succesfully parsed some tables from an html page using this code:

foreach($html->find('table') as $table) {
echo '<table>';
echo $table->innertext;
echo '</table>';
}

Now I'd like to parse some more code, look at the source html below:

<h5>.....</h5>
<table>.....</table>
<h5>.....</h5>
<table>.....</table>
<h5>.....</h5>
<table>.....</table>

I tried this code:

foreach($html->find('h5') as $h5) {
echo '<h5>';
echo $h5->innertext;
echo '</h5>';
}
foreach($html->find('table') as $table) {
echo '<table>';
echo $table->innertext;
echo '</table>';
}

This is the output:

<h5>.....</h5>
<h5>.....</h5>
<h5>.....</h5>
<table>.....</table>
<table>.....</table>
<table>.....</table>

How can I do to preserve the original order? Thanks!

2 Answers 2

3

You have to get and loop over all nodes at once

foreach($html->find('h5, table') as $node) { // or ->find('*')
    echo '<' . $node->tag . '>'; // $node->tag = 'h5' for a h5-element, and so on
    echo $node->innertext;
    echo '</' . $node->tag . '>';
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much for your help! It looks like it's working as intended. One more question: how can I add a class to table tags?
I suggest you read the simplehtmldom documentation (although it is very minimal...). You can easily read out an node's class with $tableClass = $node->class
Thanks I was able to add classes with this code: foreach($html->find('h5, .table') as $node) { echo '<' . $node->tag . ' class="live-data">'; // $node->tag = 'h5' for a h5-element, and so on echo $node->innertext; echo '</' . $node->tag . '>';
0

Thanks I was able to add classes with this code:

foreach($html->find('h5, .table') as $node) {
echo '<' . $node->tag . ' class="myclass">';
echo $node->innertext;
echo '</' . $node->tag . '>';

2 Comments

.table? I don't know this parser but this looks like a class selector.
Yes I only needed to parse tables with class="table".

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.