【发布时间】:2016-01-28 15:12:35
【问题描述】:
我有以下 XML 文件
<Item>
<name>...</name>
<id>...</id>
<ImageSets>
<ImageSet Category="variant">
<SwatchImage>
<URL>...</URL>
<Height Units="pixels"></Height>
<Width Units="pixels"></Width>
</SwatchImage>
<SmallImage>
<URL>...</URL>
<Height Units="pixels"></Height>
<Width Units="pixels"></Width>
</SmallImage>
</ImageSet>
<ImageSet Category="primary">
<SwatchImage>
<URL>...</URL>
<Height Units="pixels"></Height>
<Width Units="pixels"></Width>
</SwatchImage>
<SmallImage>
<URL>...</URL>
<Height Units="pixels"></Height>
<Width Units="pixels"></Width>
</SmallImage>
</ImageSet>
</ImageSets>
</Item>
<Item>....</Item>
然后我使用 PHP 遍历文件中的 Item 节点。
foreach ($Xml as $item){
$name = $item->name;
$ID = $item->id;
};
等等。该代码可以完美地为每个项目提取名称和 ID。
现在我的问题是提取 ImageSet Category='primary'->SmallImage->URL。 ImageSet 节点不按任何特定顺序排列,因此有时“主要”会在前,有时会出现“变体”,这就是 $item->ImageSets->ImageSet[1] 不是解决方案的原因
所以在我的主 foreach 循环中,我尝试使用 xpath,如下所示:
$src='';
foreach ($item->ImageSets->xpath('//ImageSet[@Category="primary"]') as $img){
$src = $img->MediumImage->URL;
};
绝对没有运气。
任何想法都将不胜感激。
【问题讨论】: