Jump to content

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


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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

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.   Restore formatting

  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.

×
×
  • 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.