Search code examples
phpxmlwriter

Defining Variables or constant in XMLwriter PHP


i am new in PHP. Using xmlwriter to produce an xml file. I have below code.

$xml = new XMLWriter(); 
$xml->openURI('test.xml');

$xml->setIndent(true);
$mmmid = '1981';


$xml->startDocument('1.0', 'UTF-8');
$xml->text('<raml xmlns="raml21.xsd" version="2.1">');
$xml->text('    <cmData scope="all" type="plan">'); 
$xml->text('        <header>');

$xml->text('            <log dateTime="2012-11-05T12:27:50+02:00" appInfo="Manager" user="WebUI" appVersion="4.5133.90" action="created"/>');

$xml->text('        </header>');    

$xml->text('                    <managedObject class="MRBTS" distName="IDENTITY-'$mmmid'" operation="create" version="1803">');
$xml->text('                    <p name="btsName">B1123</p>');
$xml->text('                </managedObject>');

I want to define the mmmid in the output of xml file, so it will be appeared in the output distName="IDENTITY-1981"

How can i define variable mmmid in the code and expected printed in output of the text above?

Thank you a lot, Br,FM


Solution

  • When concatenating a variable with strings in PHP there are several ways of doing it.

    Use double quotes " as surrounding delimiters

    When using double quotes " in PHP you can use variables inside the string as usual

    $foo = 4;
    echo "Hello $foo";
    

    Output:

    Hello 4
    

    This would give the following solution for your problem:

    # Note that you need to escape the original double quotes with a backslash
    $xml->text("<managedObject distName=\"IDENTITY-$mmmid\" operation=\"create\" version=\"1803\">');
    

    Concatenate with a dot .

    Another way of binding a variable with text is by using a dot . between the variable and string (this also works with only strings or only variables as well). For this method you can use either single ' or double quotes ".

    $foo = 4;
    echo 'Hello ' . $foo;
    

    Output

    Hello 4
    

    And with this method it would give you this

    $xml->text('<managedObject distName="IDENTITY-' . $mmmid . '" operation="create" version="1803">');