XPath savehtml 删除父元素 [英] XPath savehtml remove parent element

查看:61
本文介绍了XPath savehtml 删除父元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在父元素中获取 HTML.例如,我有这样的结构:

<div>text<b>more text</b>和<i>更多</i></div>

我想得到 textmore text</b>and <i> some more</i> 结果.

这是我的代码:

$dom = new DOMDocument();$dom->loadhtml($html);$xpath = new DOMXPath($dom);$text = $xpath->query("//div/div");$html = $dom->saveHTML($text->item(0));

结果是

<div>text<b>more text</b>and <i>some more</i></div>

我想过使用 preg_replace 但这不是一个好主意.如何使用 XPath 删除父元素?

解决方案

您可能需要

$html = '';foreach ($text->item(0)->childNodes as $child) {$html .= $dom->saveHTML($child);}

这是迭代div元素节点的子节点的伪代码,我希望我的PHP语法正确.

I want to get the HTML inside the parent element. For example, I have this structure:

<div>
<div>text<b>more text</b>and <i>some more</i></div>
</div>

and I want to get text<b>more text</b>and <i>some more</i> as a result.

Here's my code:

$dom = new DOMDocument();
$dom->loadhtml($html);
$xpath = new DOMXPath($dom);
$text = $xpath->query("//div/div");
$html = $dom->saveHTML($text->item(0));

And the result is

<div>text<b>more text</b>and <i>some more</i></div>

I thought of using preg_replace but it's not a good idea. How can I remove the parent element using XPath?

解决方案

You might need

$html = '';
foreach ($text->item(0)->childNodes as $child) {
  $html .= $dom->saveHTML($child);
}

That's pseudo code iterating over the child nodes of the div element node, I hope I got the PHP syntax right.

这篇关于XPath savehtml 删除父元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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