2

I need to find a way to urlencode the values within xml tags but keeping the tags intact using PHP. Maybe it's possible using an regular expression checking for begin tags and end tags with no tags within the element. Or it might be better to look for data between > and </ without one of either within the data.

<?xml version="1.0"?>
<catalog>
   <book>
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications with XML.</description>
   </book>
   <book>
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description>
   </book>
</catalog>

Should become:

<?xml version="1.0"?>
    <catalog>
       <book>
          <author>Gambardella%2C+Matthew</author>
          <title>XML+Developer%27s+Guide</title>
          <genre>Computer</genre>
          <price>44.95</price>
          <publish_date>2000-10-01</publish_date>
          <description>An+in-depth+look+at+creating+applications+with+XML.</description>
       </book>
       <book>
          <author>Ralls%2C+Kim</author>
          <title>Midnight+Rain</title>
          <genre>Fantasy</genre>
          <price>5.95</price>
          <publish_date>2000-12-16</publish_date>
          <description>A+former+architect+battles+corporate+zombies%2C+an+evil+sorceress%2C+and+her+own+childhood+to+become+queen+of+the+world.</description>
       </book>
    </catalog>

EDIT In the end i changed the process, eliminating this problem.

Accepted the answer since i'd probably do the trick for other people

1
  • Can you explain why you need to urlencode these textnode values? Commented Apr 1, 2013 at 10:41

1 Answer 1

3

This is fairly simple to do with DOMDocument / DOMXPath. You can just query for all non-empty text nodes and update them with urlencoded text.

$dom = new DOMDocument;
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//text()[normalize-space()]') as $textNode) {
    $textNode->parentNode->replaceChild($dom->createTextNode(
        urlencode($textNode->nodeValue)), $textNode);
}
echo $dom->saveXML();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I will try this at work tomorrow and accept this answer if it solved the problem.

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.