使用 PHP Simple DOM Parser 进行递归 [英] Recursion using PHP Simple DOM Parser

查看:45
本文介绍了使用 PHP Simple DOM Parser 进行递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于某种原因,我在使用 Simple DOM Parser Library 时遇到了递归.

我的 HTML 就像

<div class="some_div">一些文字</div><div class="field_1 misc1"><a href="#">一些文本链接</a><strong>15</strong></div><div class="field_2 misc2"><a href="#">一些文字链接</a><strong>25</strong></div>

我创建了 PHP 脚本,包含单个文件

include_once('simple_html_dom.php');

我尝试从上面的 HTML 中获取 15 和 25 个值.但是当我跑

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

我的脚本返回了很多递归 - 我做错了什么,如何正确获取这 15 和 25 值?

解决方案

不要在 DOM 对象上使用 print_r()var_dump().DOM 对象具有引用其子项和父项的属性.所以当它打印子元素时,它需要打印它的父属性.并且当它打印父级时,它需要再次打印子级,因此陷入无限递归.

如果你想得到 1525,你应该使用匹配这些元素的选择器.然后循环遍历结果并打印文本.

$ret = $html->find('#root strong');foreach ($ret as $field) {echo $field->plaintext;}

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?

解决方案

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;
}

这篇关于使用 PHP Simple DOM Parser 进行递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆