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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?