-2

I want to create dynamic tags in XML using PHP

like this : <wsse:Username>fqsuser01</wsse:Username>

the main thing is that I want the tags will change the value inside ---> "wsse" (like this value)

what I need to do? to create this XML file wite PHP?

Thanks,

adi
  • 81
  • 7
  • Possible duplicate of [How to generate XML file dynamically using PHP?](http://stackoverflow.com/questions/486757/how-to-generate-xml-file-dynamically-using-php) – ThW Apr 06 '17 at 08:40

2 Answers2

1

For this purpose you can use XMLWriter for example (another option is SimpleXML). Both option are in PHP core so any third party libraries aren't needed. wsse is a namespace - more about them you can read here
I also share with you some example code:

<?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(); 
?>

Result:

<?xml version="1.0"?>
<root>
 <r1:id>1</r1:id>
 <r2:id>2</r2:id>
 <r3:id>3</r3:id>
</root>
Starspire
  • 272
  • 3
  • 15
0

You could use a string and convert it to XML using simplexml_load_string(). The string must be well formed.

<?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);
?>

If you wanted to be able to change the namespaces on each XML element you would do something very similar to what is shown above. (Form a string with dynamic namespaces)

The XML portion that I instructed you to backspace all of the way has weird behavior. See https://www.w3schools.com/php/func_simplexml_load_string.asp for an example that you can copy & paste.

MackProgramsAlot
  • 583
  • 1
  • 3
  • 16