【问题标题】:XML replace & (PHP)XML 替换 & (PHP)
【发布时间】:2023-03-06 09:31:01
【问题描述】:

我有问题。在我的 XML 文件中,一些值的名称包含:

&

如何用普通的 "&" 替换它? 我试过这个,但它不工作....

这只是名称,所以它是否被双重转义并不重要......

<product>
    <title>Command &amp; Conquer 3tiberium Wars</title>
    <url>http://www.onlinekeystore.com/command-and-conquer-3-tiberium-wars-cd-key-origin.html</url>
    <priceEUR>7.99</priceEUR>
  </product>

我的代码不工作:

$string= str_replace("&amp;", ' & ', $string);

问候和感谢!

【问题讨论】:

  • 你能给我们更多的代码吗?你是如何输出代码等的。
  • 为什么需要更换? & 不是一个有效的 XML 字符,这就是它被 & 转义的原因
  • 我想替换它,因为我要用 WP All Import 导入这个 XML,我不知道这是否会改变它
  • 不要告诉我们它不起作用。告诉我们它是如何失败的。

标签: php regex xml replace


【解决方案1】:

这段代码没有错

$string= str_replace("&amp;", ' & ', $string);

您确定将 xml 字符串存储在 $string 变量中吗? 能给我们更多的代码吗?

【讨论】:

  • 我完全确定。我的意思是我有很多其他替代品,它们工作正常! (在 & 替换下方的相同函数中。是的,我正确存储它: $word = $marker->item($i)->textContent; $escapedWord = escapWord($word);
【解决方案2】:

我的代码:

函数 loadTitles($tagName, $path){

$dom = new DOMDocument('1.0', 'utf-8');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->load($path);

$marker = $dom->getElementsByTagName($tagName);

for ($i = $marker->length - 1; $i >= 0; $i--) {
    $word = $marker->item($i)->textContent;
    $escapedWord = escapWord($word);
    $marker->item($i)->textContent = $escapedWord;
}

$dom->saveXML();
$dom->save($path);
}


function escapWord($string){

    $replaceNothing = [":", ",", ";", "`", "#", "'", "´", "–", "!", "(", ")", ".", "@", "’", "+", "™"];
    $replaceSpace = ["-", "–", "_", "/"];
    $delete = ["Steam", "Eu", "Key"];

    $string= str_replace("&amp;", ' & ', $string);

return $string;

【讨论】:

    【解决方案3】:

    您正在向我们展示包含 &amp;amp; 的词法 XML,但您的代码正在处理 DOM。 DOM 可能是解析词法 XML 的结果,解析器所做的一件事就是将 &amp;amp; 替换为 &amp;amp;。这不是你需要自己做的事情。

    当您将 DOM 序列化/保存为词法 XML 时,当然过程会颠倒过来,&amp;amp; 会被 &amp;amp; 替换。如果序列化程序不这样做,那么生成的 XML 格式就会不正确。

    【讨论】:

      猜你喜欢
      • 2013-07-11
      • 2023-03-26
      • 1970-01-01
      • 2011-06-06
      • 2013-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-13
      相关资源
      最近更新 更多