Recursion using PHP Simple DOM Parser

2019-07-23 11:02发布

For some reason I get recursion while using Simple DOM Parser Library.

My HTML is like

<div id="root">
    <div class="some_div">some text</div>
    <div class="field_1 misc1"><a href="#">Some text link</a> <strong>15</strong></div>
    <div class="field_2 misc2"><a href="#">Some text link</a> <strong>25</strong></div>
</div>

I created PHP script, included single file

include_once('simple_html_dom.php');

And I try to get 15 and 25 values from HTML above. But when I run

$ret = $html->find('div[id=root]'); 
print_r($ret);

my script returns a lot of recursions - what am i doing wrong and how can i get this 15 and 25 values properly?

1条回答
迷人小祖宗
2楼-- · 2019-07-23 11:50

Don't use print_r() or var_dump() on DOM objects. The DOM object has properties that refer to its children and parent. So when it prints the child element, it then needs to print its parent property. And when it prints the parent, it needs to print the child again, so it gets into an infinite recursion.

If you want to get 15 and 25, you should use a selector that matches those elements. Then loop through the results and print the text.

$ret = $html->find('#root strong');
foreach ($ret as $field) {
    echo $field->plaintext;
}
查看更多
登录 后发表回答