2016-03-26 18 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; 
    } 

私は$ DOMDocumentを返しました。それから私はこれをした

$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(); 
     } 

と私は正しい結果を得た。

関連する問題