使用php和xpath获取父元素的内部HTML [英] Get inner HTML of parent element with php and xpath

查看:101
本文介绍了使用php和xpath获取父元素的内部HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取所有内容,包括父元素的标签,比如:

$imgs = $xpath->query('//img');
echo $imgs->item(0)->parentNode->innerHTML;

当然,innerHTML属性不存在.最相似的属性是innerText,该属性仅包含不带标签的文本.我真的需要HTML.有没有轻松的方法可以实现这一目标?

解决方案

您可以使用另一个XPath表达式(选择父节点和innerHTML)来选择父元素../../node().

使用node()很重要,这样您就可以同时获得元素和文本节点.

如果您知道只有一个<img/>元素,则也可以使用//*[img]/node().

I'd like to get all of the content including tags of a parent element, let's say:

$imgs = $xpath->query('//img');
echo $imgs->item(0)->parentNode->innerHTML;

Of course, innerHTML attribute doesn't exist. The most similar attribute would be innerText that contains only text without tags. I really need the HTML. Is there a painless way to achieve this?

解决方案

You could use another XPath expression instead (of selecting the parent node and innerHTML), ./../node() which selects the parent element.

Using node() is important so you get both elements and text nodes.

If you know theres only one <img/> element, you can also use //*[img]/node().

这篇关于使用php和xpath获取父元素的内部HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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