2017-04-05 105 views
-2

我想用PHP創建XML格式的動態代碼如何將數據XML標籤裏面

這樣的:<wsse:Username>fqsuser01</wsse:Username>

主要的是我想要的標籤會改變裏面的值---> 「wsse」 (喜歡這個值)

我需要做什麼?創建這個XML文件wite PHP?

感謝,

+0

的可能的複製[如何動態地使用PHP生成XML文件?](http://stackoverflow.com/questions/486757/how-to-generate-xml-file-dynamically-using-php) – ThW

回答

1

爲此,您可以使用XMLWriter例如(另一個選項是SimpleXML)。這兩個選項都在PHP核心中,因此不需要任何第三方庫。 wsse是一個命名空間 - 更多關於他們,你可以閱讀here
我也跟大家分享一些示例代碼:

<?php 

//create a new xmlwriter object 
$xml = new XMLWriter(); 
//using memory for string output 
$xml->openMemory(); 
//set the indentation to true (if false all the xml will be written on one line) 
$xml->setIndent(true); 
//create the document tag, you can specify the version and encoding here 
$xml->startDocument(); 
//Create an element 
$xml->startElement("root"); 
//Write to the element 
$xml->writeElement("r1:id", "1"); 
$xml->writeElement("r2:id", "2"); 
$xml->writeElement("r3:id", "3"); 
$xml->endElement(); //End the element 
//output the xml 
echo $xml->outputMemory(); 
?> 

結果:

<?xml version="1.0"?> 
<root> 
<r1:id>1</r1:id> 
<r2:id>2</r2:id> 
<r3:id>3</r3:id> 
</root> 
+0

@adi如果它可以幫助你,請將答案標記爲已接受。 – Starspire

+0

是的,我會試試這個謝謝 – adi

0

你可以使用一個字符串,並使用simplexml_load_string其轉換爲XML()。該字符串必須形成良好。

<?php 
    $usernames= array(
     'username01', 
     'username02', 
     'username03' 
    ); 
    $xml_string = '<wsse:Usernames>'; 
    foreach($usernames as $username){ 
     $xml_string .= "<wsse:Username>$username</wsse:Username>"; 
    } 
    $xml_string .= '</wsse:Usernames>'; 
    $note= 
    <<<XML 
    $xml_string 
    XML; //backspace this line all the way to the left 
    $xml=simplexml_load_string($note); 
?> 

如果您希望能夠更改每個XML元素上的命名空間,您將執行與上面顯示內容非常相似的操作。 (用動態命名空間構成一個字符串)

我指示你退格的XML部分有一些奇怪的行爲。有關可以複製&粘貼的示例,請參見https://www.w3schools.com/php/func_simplexml_load_string.asp