SimpleXMLElement Access elements with namespace?

后端 未结 2 738
自闭症患者
自闭症患者 2020-12-22 02:31

I have the following XML:


    
                 


        
相关标签:
2条回答
  • 2020-12-22 03:08

    You need to use the ->children() method. If you avoid XPath and just use the SimpleXML operators, your code will end up much simpler.

    Namespaced elements are also one of many things not visible when using standard PHP debug functions to debug the rather magical SimpleXML objects. (The below uses [my simplexml_dump() function instead.)

    $data = new SimpleXMLElement($xml);
    $banner = $data->children('ns1', true)->return; 
    // Or to avoid relying on the 'ns1' alias: ->children('http://endpoint.website.com/', false);
    simplexml_dump($banner);
    

    Note that the 'ns1' namespace remains selected until another ->children() call:

    // Remember to cast to string if you want the content of an element or attribute
    var_dump( (string)$banner->linkName );
    

    If <return> can occur multiple times, this obviously becomes:

    foreach ( $data->children('ns1', true)->return as $banner )
    {
        simplexml_dump($banner);
    }
    
    0 讨论(0)
  • 2020-12-22 03:21

    All you need is

    $data = new SimpleXMLElement($xml);
    $data->registerXPathNamespace('ns1','http://endpoint.websitecom/');
    $part = $data->xpath("//ns1:return");
    var_dump($part[0]->children("ns1",true));
    

    Output

    object(SimpleXMLElement)[3]
      public 'campaignID' => string '0' (length=1)
      public 'categoryID' => string '200230455' (length=9)
      public 'categoryName' => string 'Promotion' (length=9)
      public 'linkID' => string '10001599' (length=8)
      public 'linkName' => string 'KFL-20% off No Min' (length=18)
      public 'mid' => string '3071' (length=4)
      public 'nid' => string '1' (length=1)
      public 'clickURL' => string '
                http://someurl
            ' (length=36)
      public 'endDate' => string 'Oct 15, 2012' (length=12)
      public 'height' => string '250' (length=3)
      public 'iconURL' => string '
                http://someurl
            ' (length=36)
      public 'imgURL' => string '
                http://someurl
            ' (length=36)
      public 'landURL' => string '
                http://someurl
            ' (length=36)
      public 'serverType' => string '22' (length=2)
      public 'showURL' => string '
                http://someurl
            ' (length=36)
      public 'size' => string '13' (length=2)
      public 'startDate' => string 'Oct 14, 2012' (length=12)
      public 'width' => string '300' (length=3)
    
    0 讨论(0)
提交回复
热议问题