Jump to content

PHP - Update XML File - Re-Save As XML File


stig1

Recommended Posts

I have an xml file that I require to search and locate tags / data to update an modify, and re-save as an xml file.

 

For example:

Locate <DeliveryStateCode>NT </DeliveryStateCode> and replace with <DeliveryStateCode>NT</DeliveryStateCode>

 

There could be many records within the xml file using the <DeliveryStateCode></DeliveryStateCode> tags.

 

Otherwise, if there is a solution to just remove the space at the end of the data- <DeliveryStateCode>NT </DeliveryStateCode> throughout the xml file within the <DeliveryStateCode></DeliveryStateCode> tags, that would work aswell.

 

Been having trouble figuring this out.

 

Look forward to hearing some responses, and thankyou in advance :)

Link to comment
https://forums.phpfreaks.com/topic/268169-php-update-xml-file-re-save-as-xml-file/
Share on other sites

Removing trailing spaces? Do you want to do it with all tags or just certain ones?

 

If the former then a (gasp) regex on the file contents would be easy:

>(\S+([ \t]+\S+)*)[ \t]+

Replace with $1.

 

Otherwise pull the XML into memory with SimpleXML (or DOMDocument if you must), search for the tags, trim() the contents, and write the XML back out.

You know what? I suspect this is just a one-time thing. It'll be quicker and easier to use a regex: it'll does what you need and will preserve any formatting in the file.

 

Use preg_replace to replace

#(\S+)\s+#

with

$1

(and to anybody watching: yes, I could have used assertions, I just don't use them out of habit)

 

You can use file_get_contents to read the file and file_put_contents to write it back out.

Archived

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

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.