2016-03-26 81 views
-1

我使用此代碼xml_encode我的數組。php xml_encode將屬性設置爲特定的標記名

public function xml_encode($mixed, $domElement=null, $DOMDocument=null) { 
    if (is_null($DOMDocument)) { 
     $DOMDocument =new DOMDocument; 
     $DOMDocument->formatOutput = true; 
     $this->xml_encode($mixed, $DOMDocument, $DOMDocument); 
     echo $DOMDocument->saveXML(); 
    } 
    else { 
     // To cope with embedded objects 
     if (is_object($mixed)) { 
      $mixed = get_object_vars($mixed); 
     } 
     if (is_array($mixed)) { 
      foreach ($mixed as $index => $mixedElement) { 
       if (is_int($index)) { 
        if ($index === 0) { 
         $node = $domElement; 
        } 
        else { 
         $node = $DOMDocument->createElement($domElement->tagName); 
         $domElement->parentNode->appendChild($node); 
        } 
       } 
       else { 
        $plural = $DOMDocument->createElement($index); 
        $domElement->appendChild($plural); 
        $node = $plural; 
        if (!(rtrim($index, 's') === $index)) { 
         $singular = $DOMDocument->createElement(rtrim($index, 's')); 
         $plural->appendChild($singular); 
         $node = $singular; 
        } 
       } 

       $this->xml_encode($mixedElement, $node, $DOMDocument); 
      } 
     } 
     else { 
      $mixed = is_bool($mixed) ? ($mixed ? 'true' : 'false') : $mixed; 
      $domElement->appendChild($DOMDocument->createTextNode($mixed)); 
     } 
    } 
} 

https://www.darklaunch.com/2009/05/23/php-xml-encode-using-domdocument-convert-array-to-xml-json-encode

,而且運作良好。現在,我想將屬性設置爲特定的標籤。

比方說,這是我的xml。

<book> 
    <title>PHP Programming</title> 
    <description>Learn how to code in PHP</description> 
</book> 

我想要的屬性設置爲冠軍標籤,並使其

<title name=attributeValue> 
     PHP Programming 
</title> 

我怎樣才能做到這一點?

謝謝!

回答

0

只是爲了與大家分享,如果別人也有這樣的問題。 我剛剛解決了我的問題。 在這部分

if (is_null($DOMDocument)) { 
     $DOMDocument =new DOMDocument; 
     $DOMDocument->formatOutput = true; 
     $this->xml_encode($mixed, $DOMDocument, $DOMDocument); 
     //echo $DOMDocument->saveXML(); 
     return $DOMDocument; 
    } 

我返回$ DOM文檔。然後我做了這個

$xml = $this->xml_encode($data); 
    $xmlstring = $xml->saveXML(); 
     $dom = new DOMDocument(); 
     $dom->loadXML($xmlstring); 

     foreach ($dom->getElementsByTagName('title') as $item) { 
      $item->setAttribute('name', 'attributeValue'); 
      echo $dom->saveXML(); 
     } 

我得到了正確的結果。

相關問題