0

I am looking for a way to delete part of a string from an xml file. At the moment i have some content like so:

<description>blah blah blah blah</description>

I would like to use a function to find

<description> & </description>

and delete the content between. It would also need to repeat this throughout the xml document to remove any content between further description tags.

Im not sure how to start at attempting this and any sample code would be much appreciated.

2
  • 1
    preg_replace might help. Eg: $xml = preg_replace("~(<description>).*?(<description>)~msi", "$1$2", $original_xml); Commented Feb 1, 2012 at 11:06
  • how to parse html/xml has been answered before. can you please be more specific about your scenario. are there literal ampersands in your code and you need to fix them? Commented Feb 1, 2012 at 11:16

1 Answer 1

1

If your document is fully XML, you can use the DOMDocument extension to manipulate it. See especially http://www.php.net/manual/en/domdocument.getelementsbytagname.php You could write something like:

$dom = new DOMDocument;
$dom->loadXML(' YOUR XML CODE HERE ');
$descriptions = $dom->getElementsByTagName('description');
foreach ($descriptions as $description) {
   $description->nodeValue = '';
}
$xml = $dom->saveXML();
Sign up to request clarification or add additional context in comments.

2 Comments

this doesnt explain how to get the elements containing an ampersand. also, if there is literal ampersands in the XML, the OP likely cannot open the document with DOM because ampersands denote entities.
He said "to remove any content between further description tags." so I assumed the ampersand was just a placeholder. Obivously a small test is needed in the foreach loop if he only wants to remove when nodeValue is " & ". As for the litteral ampersand, it is true, hence "If your document is fully XML".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.