2

我需要找到一种方法来对 xml 标签中的值进行 urlencode,但使用 PHP 保持标签完整。也许可以使用正则表达式检查元素中没有标签的开始标签和结束标签。或者,最好在数据中查找介于两者之间>和之间</的数据。

<?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>

应该变成:

<?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>

编辑 最后我改变了过程,消除了这个问题。

接受了答案,因为我可能会为其他人做这个把戏

4

1 回答 1

3

使用 DOMDocument / DOMXPath 非常简单。您可以只查询所有非空文本节点并使用 urlencoded 文本更新它们。

$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();
于 2013-03-28T23:35:38.153 回答