Jump to content
Sign in to follow this  
Chrex

Using PHP - How to create a variable in XML?

Recommended Posts

Hi guys,

I try to build an xml document with php. Creating, saving and sending works fine. Just couldnt figure out how to insert a variable to my php-code, which creates the xml.

<?php$xml = new DOMDocument("1.0", "utf-8";$root = $xml->createElement("ABC");$xml->appendChild($root);$var1 = $xml->createElement("Town");$var1Text = $xml->createTextNode('$townname');$var1->appendChild($varText);$BCD = $xml->createElement("Data");$BCD->appendChild($var1);$root->appendChild($BCD);$xml->formatOutput = true;echo "<xmp>". $xml->saveXML() ."</xmp>";$xml->save("energieausweis.xml") or die("Error");?>

Instead of using a fix "createTextNode" I wanna use a variable. Something like "createVariableNode" (I know that this doesnt exist).

Hope you guys understand me. I get a variable from a form, lets say $townname, which can be Vancouver or Paris. This variable shall be written in my xml. Depending on the selection from the form, my xml shall contain Vancouver or Paris and not just the text "$townname".

 

Thanks a lot for your help!

Share this post


Link to post
Share on other sites

The XML language doesn't have variables.

 

If you want the contents of a PHP variable in your XML document, just pass the variable to the function:

$value = 'Some text';$textNode= $xml->createTextNode($value);

When using variables in PHP you don't wrap them in quotation marks, especially not single quotes. In PHP single quotes print out literally what is between them. Double quotes print text, special characters and variables. If all you want is the value of the variable itself, then don't use any quotation marks at all. The variable has the value in it already.

  • Like 1

Share this post


Link to post
Share on other sites

Thanks for the hint!

I took my value from the session and did it like this:

	$value = $_SESSION['name'];	$valueText = $xml->createTextNode($value);

It works :)

Edited by Chrex

Share this post


Link to post
Share on other sites

You could even put $_SESSION['name'] right in the function.

  • Like 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...