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

PHP使用XPath解析XML,指定ProductCode返回空数组问题

问题分析与解决

你的代码返回空数组的核心原因是XPath表达式错误:你用@ProductCode来匹配,但XML中的ProductCode是Product节点的子元素,而非节点属性(属性是类似<Product ProductCode="xxx">这种写法)。

修正后的代码

$refsku = '476521Az-f';

$xml = file_get_contents($cache_url_use);
$xml_parse = simplexml_load_string($xml, null, LIBXML_NOCDATA);

// 修正XPath:匹配子元素ProductCode的文本值
$results = $xml_parse->xpath("/ROOT/Products/Product[ProductCode='" . $refsku . "']");

echo "<br><pre>"; print_r($results); echo "</pre>";

关键说明

  • 原表达式里的@符号是用来定位XML节点的属性,但你的XML里ProductCode是独立的子节点,所以要去掉@,改为直接匹配子元素的文本内容。
  • 给$refsku加上单引号,避免特殊字符导致XPath语法错误,养成这个习惯能适配更多复杂的编码格式。

验证效果

执行修正后的代码后,$results会包含匹配到的Product节点对象,你可以通过$results[0]->ProductName、$results[0]->Price等方式直接访问产品的各个字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 14:50:31