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