【问题标题】:How to get element value of xml in php array? [duplicate]如何在php数组中获取xml的元素值? [复制]
【发布时间】:2014-08-03 11:53:05
【问题描述】:

我的 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) 的每个值??

我需要将所有 URL 保存在一个数组中,一个是主要的,一个是变体的。谢谢:)

【问题讨论】:

    标签: php xml


    【解决方案1】:

    您正在寻找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;
    }
    

    【讨论】:

      【解决方案2】:

      查看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 ..

      【讨论】:

        猜你喜欢
        • 2014-12-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-03
        相关资源
        最近更新 更多