php - XPath 节点到字符串

标签 php xml xslt xpath simplexml

如何选择以下节点的字符串内容:

<span class="url">
 word
 <b class=" ">test</b>
</span>

<span class="url">
 word
 <b class=" ">test2</b>
 more words
</span>

我已经尝试了一些东西

//span/text()

没有得到粗体标签

//span/string(.)

无效

string(//span)

只选择1个节点

我在 php 中使用 simple_xml,我认为唯一的其他选择是使用//span 返回:

Array
(
    [0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [class] => url
                )

            [b] => test
        )

    [1] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [class] => url
                )

            [b] => test2
        )

)

*请注意,它还会从第二个跨度中删除“更多单词”文本。

所以我想我可以通过某种方式使用 php 将数组中的项目展平? Xpath 是首选,但任何其他想法也会有所帮助。

最佳答案

$xml = '<foo>
<span class="url">
 word
 <b class=" ">test</b>
</span>

<span class="url">
 word
 <b class=" ">test2</b>
 more words
</span>
</foo>';
$dom = new DOMDocument();
$dom->loadXML($xml); //or load an HTML document with loadHTML()
$x= new DOMXpath($dom);
foreach($x->query("//span[@class='url']") as $node) echo $node->textContent;

关于php - XPath 节点到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3409168/

相关文章:

xml - 是否有 XML 多重签名的标准?

xslt - Saxon XSLT 转换后 Apache FOP 转换缓慢

xpath - 如何为每个父节点选择具有多个父节点的树中的每个不是第一个子节点

php - magento 中的 cron 作业设置

php - 使用 Laravel Migration,如何在不使用原始 SQL 查询的情况下更改列的数据类型并更新其现有数据以适应新数据类型?

php - 网页在 Chrome 移动版 (Android) 上无法正确显示

php - 从 CSV 创建嵌套对象

c# - DataTable 不支持从 Xml 进行架构推断。?

java - 如何使用java正则表达式过滤html文件内容?

c# - XSLT 与 XMLDocument 数据类型 -> 使用 foreach 循环遍历节点 -> 附加到文字控件