如何在php数组中获取xml的元素值?

时间:2014-08-03 11:53:05

标签: php xml

我的XML响应如下所示:

<Items>
<Item>
 <ImageSets>
   <ImageSet Category="Primary">
      <SwatchImage>
         <URL>http://domain.com/img1.jpg</URL>
         <Height Units="pixels">30</Height>
       </SwatchImage>
       </ImageSet>

      <ImageSet Category="Variant">
       <SwatchImage>
         <URL>http://domain.com/img2.jpg</URL>
         <Height Units="pixels">30</Height>
       </SwatchImage>
       </ImageSet>

      <ImageSet Category="Variant">
       <SwatchImage>
         <URL>http://domain.com/img3.jpg</URL>
         <Height Units="pixels">30</Height>
       </SwatchImage>
      </ImageSet>

      </ImageSets>
      </Item>
      </Items>

现在,如果有多个类别,我怎样才能获得(URL)的每个值?

我需要将所有网址保存在一个数组中,一个是主数据库,另一个是变体数据库。谢谢:))

2 个答案:

答案 0 :(得分:0)

您正在寻找simpleXML

代码应该看起来像:

simplexml_load_string($xml);

foreach ($items as $item) {

/* For each <ImageSet> node, we echo a separate <SwatchImage><URL>. */
foreach ($Item->Item->ImageSets as $ImageSet) {
    echo $ImageSet->SwatchImage->URL;
}

答案 1 :(得分:0)

查看accessing attibute from simplexml

您可以访问

等元素
$data->{'parent'}->link[0]['href'] (an example)

(That is, the attributes can be accessed using standard array notation - this definitely works on single elements, not sure if it works with the additional index into the element collection.)

请查看here了解更多详情..