You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP中用XPath结合SimpleXML访问嵌入节点并提取完整文本?

问题:获取XML中Text节点下所有子节点的扁平化文本

原始XML文档

<Section>
 <Subsection lims:inforce-start-date="2003-07-01" lims:fid="182941" lims:id="182941">
  <Label>(2)</Label>
  <Text>
   In subsection (1),
    <DefinedTermEn>beer</DefinedTermEn>
   and
    <DefinedTermEn>malt liquor</DefinedTermEn>
   have the meaning assigned by section 4.
   </Text>
 </Subsection>
</Section>

遇到的问题

使用XPath语句 $xml->xpath("Body/Section/Subsection") 查询后,返回结果里的<Text>节点丢失了内部<DefinedTermEn>节点的文本,仅得到:

"In subsection (1),  and  have the meaning assigned by section 4."

需要把<Text>节点下所有子节点的内容「扁平化」,得到连续完整的文本:

"In subsection (1), beer and malt liquor have the meaning assigned by section 4."

可行解决方案

方法1:SimpleXML结合DOMDocument提取

SimpleXML直接访问节点会自动忽略子节点文本,但可以通过asXML()获取节点的完整XML,再用DOMDocument提取所有文本:

// 假设$xml是已加载的SimpleXMLElement对象
$textNodes = $xml->xpath('Section/Subsection/Text');
foreach ($textNodes as $textNode) {
    $dom = new DOMDocument();
    $dom->loadXML($textNode->asXML());
    $fullText = trim($dom->textContent);
    echo $fullText;
}

方法2:直接用DOMDocument处理

跳过SimpleXML,直接用DOMDocument加载XML并提取目标文本:

// 替换为你的XML内容
$xmlContent = '<Section>
 <Subsection lims:inforce-start-date="2003-07-01" lims:fid="182941" lims:id="182941">
  <Label>(2)</Label>
  <Text>
   In subsection (1),
    <DefinedTermEn>beer</DefinedTermEn>
   and
    <DefinedTermEn>malt liquor</DefinedTermEn>
   have the meaning assigned by section 4.
   </Text>
 </Subsection>
</Section>';

$dom = new DOMDocument();
$dom->loadXML($xmlContent);
$xpath = new DOMXPath($dom);
$textNode = $xpath->query('Section/Subsection/Text')->item(0);
$fullText = trim($textNode->textContent);
echo $fullText;

方法3:用XPath直接获取所有文本节点

调整XPath表达式,选中<Text>下的所有文本节点(包括子节点内的),再拼接成完整文本:

// 假设$xml是已加载的SimpleXMLElement对象
$textParts = $xml->xpath('Section/Subsection/Text//text()');
$fullText = trim(implode('', $textParts));
echo $fullText;

内容的提问来源于stack exchange,提问作者Gabriel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 03:33:20