duanhuang3074 2012-09-08 12:03
浏览 58
已采纳

PHP htmlentities并以xml格式保存数据

Im trying to save some data into a xml file using the following PHP script:

<?php

$string = '<a href="google.com/maps">Go to google maps</a> and some special characters ë è & ä etc.';

$string = htmlentities($string, ENT_QUOTES, 'UTF-8');

$doc = new DOMDocument('1.0', 'UTF-8');
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;

$root = $doc->createElement('top');
$root = $doc->appendChild($root);

$title = $doc->createElement('title');
$title = $root->appendChild($title);

$id = $doc->createAttribute('id');
$id->value = '1';
$text = $title->appendChild($id);

$text = $doc->createTextNode($string);
$text = $title->appendChild($text);

$doc->save('data.xml');

echo 'data saved!';

?>

I'm using htmlentities to translate all of the string into an html format, if I leave this out the special characters won't be translated to html format. this is the output:

<?xml version="1.0" encoding="UTF-8"?>
<top>
  <title id="1">&amp;lt;a href=&amp;quot;google.com/maps&amp;quot;&amp;gt;Go to google maps&amp;lt;/a&amp;gt; and some special characters &amp;euml; &amp;egrave; &amp;amp; &amp;auml; etc.</title>
</top>

The ampersand of the html tags get a double html code: &amp;lt; and an ampersand becomes: &amp;amp;

Is this normal behavior? Or how can I prevent this from happening? Looks like a double encoding.

  • 写回答

3条回答 默认 最新

  • dshm8998473 2012-09-08 12:25
    关注

    Try to remove the line:

    $string = htmlentities($string, ENT_QUOTES, 'UTF-8');
    

    Because the text passed to createTextNode() is escaped anyway.

    Update: If you want the utf-8 characters to be escaped. You could leave that line and try to add the $string directly in createElement().

    For example:

    $title = $doc->createElement('title', $string);
    $title = $root->appendChild($title);
    

    In PHP documentation it says that $string will not be escaped. I haven't tried it, but it should work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建