如何选择以下节点的字符串内容:
<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/