Jump to content

PHP - Add Tags to existing File


danalario

Recommended Posts

I need to write a little PHP nugget to add Root Element XML tags to an XML file.I've got an application that writes XML records to a file called orderdata.xml that looks like this:<record> <f_name>John</f_name> <l_name>Doe</lname></record><record> <f_name>Jane</f_name> <l_name>Mansfield</lname></record>I want to add Root Element tags called <sales> at the Top and End of the file so that the resulting file looks like<sales><record> <f_name>John</f_name> <l_name>Doe</lname></record><record> <f_name>Jane</f_name> <l_name>Mansfield</lname></record></sales>Here's the code I wrote so far...its getting the contents of the file and loading it into a string.if I echo $loadedData I get the contents of orderdata.xml correctly, I just am not sure how to proceed from here.

<?php$myFile = "orderdata.xml";$fh = fopen($myFile, 'rb');$theData = file_get_contents('./orderdata.xml', FILE_USE_INCLUDE_PATH);fclose($fh);$loadedData = htmlspecialchars($theData);?>

I thought about using the xml DOM functions to create a single element and then make the value of that element the string $loadedData but I'm not exactly sure how to do that, and it seems needlessly complicated just to write two tags.Then I thought that since I've got the data loaded as a string and I simply want to add <sales> at the start of the string and </sales> at the end, there must be a simple way to do that...right?I'm still new to PHP so I don't really know how. In my mind I'd just set two variables, $xmlstart="<sale>" and $xmlend="</sale>" and then code:$newfile = $xmlstart + $loadedData + $xmlend; So how to I actually execute that in PHP?Thanks In advance :)

Link to comment
Share on other sites

The string concatenation operator is . not +, so try this:$newfile = $xmlstart . $loadedData . $xmlend;Is there a reason you're using htmlspecialchars ? I don't know. Just asking.You do not need to use fopen before using file_get_contents. That's kinda the point behind file_get_contents. It simplifies the old Unix multi-step process.

Link to comment
Share on other sites

That makes sense if you are outputting the XML for display in an HTML context, and if that is what you want, there is nothing wrong with that technique. If you want to access the XML as a DOM Object, it will not work.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...