如何在标记XML中插入数据

时间:2017-04-05 18:56:13

标签: php xml

我想用PHP

在XML中创建动态标签

像这样:PreferenceFragment

主要的是我希望标签会改变里面的值---> “WSSE” (像这个值)

我需要做什么?用PHP创建这个XML文件?

谢谢,

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分: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。糊。