PHP's SimpleXML: How to use colons in names

前端 未结 3 1225
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-06 05:54

I am trying to generate an RSS Google Merchant, using SimpleXML.

The sample given by Google is:




        
3条回答
  •  孤街浪徒
    2020-12-06 06:09

    As @ceejayoz said, you need to add the "http://base.google.com/ns/1.0" namespace to the root node so that SimpleXML knows the namespace has already been declared and doesn't emit a duplicate prefix binding.

    I think you may need to read a tutorial on XML Namespaces, because I'm not sure you really understand what the "g:" is doing here.

    Here is a more complete example. XML:

    $xml = << 
     
       
        The name of your data feed 
        http://www.example.com 
        A description of your content 
         
          Red wool sweater 
           http://www.example.com/item1-info-page.html 
          Comfortable and soft, this sweater will keep you warm on those cold winter nights. 
          http://www.example.com/image1.jpg 
          25 
          1a 
         
       
     
    EOT 
    ; 
    

    Code:

    $rss = new SimpleXMLElement($xml); 
    $NS = array( 
        'g' => 'http://base.google.com/ns/1.0' 
    ); 
    $rss->registerXPathNamespace('g', $NS['g']); 
    $product = $rss->channel->item[0]; // example 
    
    // Use the complete namespace. 
    // Don't add "g" prefix to element name--what prefix will be used is 
    // something SimpleXML takes care of. 
    $product->addChild('condition', 'new', $NS['g']); 
    
    echo $rss->asXML(); 
    

    I usually use this pattern to deal with namespaces easily:

    $rss = new SimpleXMLElement($xml); 
    $NS = array( 
        'g' => 'http://base.google.com/ns/1.0' 
        // whatever other namespaces you want 
    ); 
    // now register them all in the root 
    foreach ($NS as $prefix => $name) { 
        $rss->registerXPathNamespace($prefix, $name); 
    } 
    // Then turn $NS to an object for more convenient syntax 
    $NS = (object) $NS; 
    // If I need the namespace name later, I access like so: 
    $element->addChild('localName', 'Value', $NS->g); 
    

提交回复
热议问题