doulao2029 2015-07-19 06:04
浏览 31
已采纳

如何使用dom文件获取div类值

how to get div class value using dom document

i need to echo this value 4,458 members

from the below code

< div class="mbs fcg">4,458 members< /div>

right now my orginal code is

$links = $dom->getElementsByTagName('div');

foreach ($links as $link){

echo $link->nodeValue;
echo $link->getAttribute('class');

}

how to target this particular class = mbc fcg ?

now with my present code i am getting all div values.

what changes i should do

  • 写回答

3条回答 默认 最新

  • dp152153 2015-07-19 07:17
    关注

    you will need to use DOMXPath, which will take a DOMDocument instance

    $xpath   = new DOMXPath( $dom );
    // if the className doesn`t changes
    $members = $xpath->query( '//div[@class="mbs fcg"]' );
    // if the class name changes ex. class="mbs fcg my-other class-name"
    $members = $xpath->query( '//div[contains(@class,"mbs fcg")]' );
    

    alternatively if you want to iterate all over your div`s you could try

    $divs = $dom->getElementsByTagName( 'div' );
    foreach( $divs as $div ){
        // if the className doesn`t changes
        if( $div->getAttribute( 'class' ) === 'mbs fcg' ){
            echo $div->nodeValue;
        }
        // if the class name changes ex. class="mbs fcg my-other class-name"
        if( strpos( $div->getAttribute( 'class' ), 'mbs fcg' ) !== false ){
            echo $div->nodeValue;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?