【问题标题】:PHP XML encoding regexPHP XML 编码正则表达式
【发布时间】:2013-03-19 14:32:28
【问题描述】:

我需要找到一种方法来对 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>

编辑 最后我改了流程,解决了这个问题。

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

【问题讨论】:

  • 您能解释一下为什么需要对这些 textnode 值进行 urlencode 吗?

标签: php xml regex urlencode


【解决方案1】:

使用 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();

【讨论】:

  • 谢谢,我明天上班试试,如果解决了问题就接受这个答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-12
相关资源
最近更新 更多