通过xpath获取div的HTML内容 [英] Get div's HTML content via xpath

查看:48
本文介绍了通过xpath获取div的HTML内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要对以下问题的支持,我有一个网站,我想通过 xpath 获取产品说明.在内容的示例 html 下方:

<span>一些测试</span><img src="一些 src"><p>一些内容等</p>

现在我使用以下代码:

$result = $xpath->query('//div[@id="description"]');

但是当我用下面的行输出结果时:

echo "

".$result->item(0)->nodeValue."

";//总是只有一个元素

我得到的只是未格式化的:一些测试内容等",没有空格和其他标签.我知道这是因为 xpath 将所有其他标签视为节点,但是...

我有办法将 div 的内容作为 HTML 获取吗?

解决方案

嘿,我之前做过类似的事情,这篇文章对我有帮助:

PHP DOMDocument/XPath:获取 HTML 文本并包围标签

这在您的代码中有点开销,我的意思是如果您认为(像我一样)可以使用不同的 XPath 查询或其他东西在一行中解决...

希望有帮助

I need a support on the following issue, I have a website where I want to get a product descriptions via xpath. Below the example html of the content:

<div id="description">
 <span>some test</span>
 <img src="some src">
 <p>
  some content etc.
 </p>
</div>

and now I use the below code:

$result = $xpath->query('//div[@id="description"]');

but when I'm outputting the result with the below line:

echo "<pre>".$result->item( 0 )->nodeValue."</pre>"; // there is always only one element

what I get is only unformatted: "some testsome content etc." with no spaces and other tags. I know it is because xpath treats all the other tags as nodes but...

I there a way to get the div's content as HTML ?

解决方案

Hey I did something similar a while back and this post helped me:

PHP DOMDocument / XPath: Get HTML-text and surrounded tags

It is a bit of overhead in your code, I mean if you thought (like me) it could be solved in one line with a different XPath query or something...

Hope it helped

这篇关于通过xpath获取div的HTML内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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