PHP遍历XML:如何获取offer的internal-id及带plan标签的image
问题描述
XML结构示例
<offer internal-id="3"> <floor>2</floor> <name>Building 1</name> <image>picture.jpg</image> <image tag="plan">plan.png</image> </offer>
当前PHP代码
$file = simplexml_load_file("feed.xml"); if($file === FALSE) die("Error"); $xml = []; foreach($file->offer as $offer) { if((string)$offer->{'location'}->{'address'} == 'Building 1') { $flat["floor"] = (string)$offer->{'floor'}; echo $flat['png']; $xml[] = $flat; } }
当前代码可正常获取floor字段,但需实现两个需求:
- 获取
offer标签的internal-id属性值 - 仅提取带有
tag="plan"的image元素内容
解决方案
1. 获取internal-id属性
在SimpleXML中,节点属性可通过数组形式直接访问,或者调用attributes()方法:
// 简洁写法 $internalId = (string)$offer['internal-id']; // 或用attributes()方法 $internalId = (string)$offer->attributes()['internal-id'];
将其加入循环,存入$flat数组即可:
$flat["internal-id"] = (string)$offer['internal-id'];
2. 筛选带tag="plan"的image元素
推荐用XPath精准匹配,效率更高:
// 查询当前offer下符合条件的image节点 $planImages = $offer->xpath('./image[@tag="plan"]'); if (!empty($planImages)) { // 取第一个匹配节点的文本内容 $flat["plan_image"] = (string)$planImages[0]; }
也可遍历所有image节点判断:
foreach($offer->image as $img) { if ((string)$img['tag'] === 'plan') { $flat["plan_image"] = (string)$img; break; // 找到目标后停止遍历 } }
修改后的完整代码
$file = simplexml_load_file("feed.xml"); if($file === FALSE) die("Error"); $xml = []; foreach($file->offer as $offer) { if((string)$offer->{'location'}->{'address'} == 'Building 1') { $flat["floor"] = (string)$offer->{'floor'}; // 获取internal-id属性 $flat["internal-id"] = (string)$offer['internal-id']; // 获取带tag="plan"的image $planImages = $offer->xpath('./image[@tag="plan"]'); if (!empty($planImages)) { $flat["plan_image"] = (string)$planImages[0]; } $xml[] = $flat; } }
内容的提问来源于stack exchange,提问作者Sergei
相关产品推荐
相关产品推荐

