PHP DOM:获取不包含子节点的NodeValue [英] PHP DOM: Get NodeValue excluding the child nodes

查看:62
本文介绍了PHP DOM:获取不包含子节点的NodeValue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量 $ content ,其中包含一段HTML代码:

I have a variable$contentcontaining a piece of HTML code :

<b>AMZN 466.00 ( 15743 ) ( <span class='red'> -1 </span>) 
MSFT 290.00 ( 37296 ) ( <span class='red'> -2 </span>)
TWTR 4,000.00 ( 20 ) ( <span class=''> 0 </span>)</b>

现在,我想要< b> 使用PHP DOM排除< span> 的值。如何才能做到这一点?

Now, I want the values of <b>excluding the values of <span> using PHP DOM. How can this be done? A code snippet would be helpful.

到目前为止,我已经尝试过:

So far, I've tried this:

$dom = new domDocument;
@$dom->loadHTML($content);
$contents_i_want = $dom->getElementsByTagName('b');
foreach($contents_i_want as $content_i_want){ 
   $filtered_content = $content_i_want->nodeValue;
   echo $filtered_content;
}


推荐答案

希望这对您有所帮助..

Hope this will help you out..

> 在此处尝试此代码段 >

<?php
ini_set('display_errors', 1);
$string='<html><body><b>AMZN 466.00 ( 15743 ) ( <span class=\'red\'> -1 </span>) 
MSFT 290.00 ( 37296 ) ( <span class=\'red\'> -2 </span>)
TWTR 4,000.00 ( 20 ) ( <span class=\'\'> 0 </span>)</b></body></html>';

$dom = new DOMDocument();
$dom->loadHTML($string);
$dom->getElementsByTagName("b");

$xpath= new DOMXPath($dom);
$result=$xpath->query("//b/span");//here we are querying domdocument to find span which is inside b.

$nodesToRemove=array();//here we are maintaining an array of nodes which we want to remove
foreach($result as $node)
{
    $node->parentNode->removeChild($node);//removing nodes from its parent
}
 echo $dom->getElementsByTagName("b")->item(0)->textContent;//displaying content after removing nodes.

输出:

AMZN 466.00 ( 15743 ) ( ) 
MSFT 290.00 ( 37296 ) ( )
TWTR 4,000.00 ( 20 ) ( )

这篇关于PHP DOM:获取不包含子节点的NodeValue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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