PHP XPath。如何返回带html标签的字符串?
<?php
libxml_use_internal_errors(true);
$html = '
<html>
<body>
<div>
Message <b>bold</b>, <s>strike</s>
</div>
<div>
<span class="how">
<a href="link" title="text">Link</a>, <b> BOLD </b>
</span>
</div>
</body>
</html>
';
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->strictErrorChecking = false;
$dom->recover = true;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$messages = $xpath->query("//div");
foreach($messages as $message)
{
echo $message->nodeValue;
}
此代码返回“消息粗体,删除链接,粗体”,不带 html 标签...
我想输出以下代码:
Message <b>bold</b>, <s>strike</s>
<span class="how">
<a href="link" title="text">Link</a>, <b> BOLD </b>
</span>
你能帮我吗?
<?php
libxml_use_internal_errors(true);
$html = '
<html>
<body>
<div>
Message <b>bold</b>, <s>strike</s>
</div>
<div>
<span class="how">
<a href="link" title="text">Link</a>, <b> BOLD </b>
</span>
</div>
</body>
</html>
';
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->strictErrorChecking = false;
$dom->recover = true;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$messages = $xpath->query("//div");
foreach($messages as $message)
{
echo $message->nodeValue;
}
This code returns "Message bold, strike Link, BOLD " without html tags...
I want to output the following code:
Message <b>bold</b>, <s>strike</s>
<span class="how">
<a href="link" title="text">Link</a>, <b> BOLD </b>
</span>
Can you help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
saveHTML()
Use
saveHTML()
我可以使用 SimpleXML 快速完成(如果您可以的话)从 DOMDocument 和 DOMXPath 切换,可能您会采用我的解决方案):
I can do it using SimpleXML really quickly (if it's okay for you to switch from DOMDocument and DOMXPath, probably you will go with my solution):