如何在DOM和PHP中获取文本节点? [英] how to fetch text nodes in DOM and PHP?

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

问题描述

我有以下代码来检索HTML文档中的所有超链接

I have the following code to retrieve all hyper links in an HTML document

,我的问题是如何检索每个锚标签内的文本节点

and my question is how to retrieve the text nodes inside every anchor tag

(即使文本节点是子节点的子节点,如果该节点的节点具有一个文本节点)?

(even if the text node is a child of a child like if the anchor node has a span node which has a text node)?

     <?PHP
               $content = "
               <html>
               <head>
               <title>bar , this is an example</title>
               </head>
               <body>
               <a href='aaa'><span>bbb</span></a>
               </body>
               </html>
               ";




        $dom = new DOMDocument();
        @$dom->loadHTML($content);
        $xpath = new DOMXPath($dom);
        $row = $xpath->evaluate("/html/body//a");

        for ($i = 0; $i < $row->length; $i++) {
            $anchor = $row->item($i);
            $href  = $anchor->getAttribute('href');
            // I want the grab the text value which is inside the anchor
            $text = //should have the value "bbb"
        }
       ?>

谢谢

推荐答案

$anchor->textContent

这里稍微有点信息 DOMNode-> textContent

:D

这篇关于如何在DOM和PHP中获取文本节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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