PHP XML 编码正则表达式

标签 php xml regex urlencode

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

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

接受答案,因为我可能会为其他人做这件事

最佳答案

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

关于PHP XML 编码正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15693949/

相关文章:

javascript REGex 删除匹配中的单引号

regex - 如何在正则表达式中包含双引号(“)

javascript - 如何从此日志输出中找到最里面的失败模式

php - 转换日期并从字符串日期 php 中删除时间

php - 将数组存储到 Javascript 中

使用 TripleDes、PKCS7 和 ECB 进行 PHP 加密/解密

php - 使用 PHP 执行特定的 MySQL 查询时如何返回数据?

java - 从输入流 Java 解析 XML

xml - 为什么外籍人士拒绝破折号字符无效?

regex - 如何编写一个 Perl 正则表达式来匹配仅包含这些字符的字符串?