title: Encoding special chars, DOMDocument XML and PHP
body: <p>Using the following characters: <code>" &amp; ' &lt; &gt; £</code> for testing. My code builds an XML file using PHP and DOMDocument. </p>
  
  <pre><code>&lt;?php
  
   $xml = new DOMDocument();
   $xml-&gt;formatOutput = true;
   $root = $xml-&gt;createElement('Start_Of_XML');
   $xml-&gt;appendChild($root);
  
   $el = $xml-&gt;createElement($node,htmlspecialchars(html_entity_decode($value[$i],ENT_QUOTES,'UTF-8'),ENT_QUOTES,'UTF-8'));               
   $parent-&gt;appendChild($el);
  
  ?&gt;
  </code></pre>
  
  <p>The <code>htmlspecialchars()</code> method above converts these chars to:</p>
  
  <p><code>" &amp;amp; ' &amp;lt; &amp;gt; £</code></p>
  
  <p>resp. That is, the double quote, apostrophe and pound sign fail to get encoded.</p>
  
  <p>If I adjust the code to use htmlentities() instead:</p>
  
  <pre><code>&lt;?
   $el = $xml-&gt;createElement($node,htmlentities(html_entity_decode($value[$i],ENT_QUOTES,'UTF-8'),ENT_QUOTES,'UTF-8'));
  
  ?&gt;
  </code></pre>
  
  <p>The chars get parsed as :</p>
  
  <p><code>" &amp;amp; ' &amp;lt; &amp;gt; &amp;pound;</code></p>
  
  <p>So the pound sign gets converted along with the rest, but again the quote and apostrophe fail to get encoded when the XML is saved.</p>
  
  <p>After searching through several posts I'm at a loss to find a solution?</p>
  
  <p>Edit:</p>
  
  <p>Using <a href="https://stackoverflow.com/questions/2822774/php-is-htmlentities-sufficient-for-creating-xml-safe-values">Gordon's</a> answer as a basis I got the results I was looking for using something along the lines of <a href="https://3v4l.org/ZksrE" rel="nofollow noreferrer">https://3v4l.org/ZksrE</a></p>
  
  <p>Great effort from <strong>ThW</strong> though. Seems pretty comprehensive. I'm going to accept this as a solution. Thanks.</p>