L
L
Lorem Ipsum2020-06-30 17:28:01
PHP
Lorem Ipsum, 2020-06-30 17:28:01

Why doesn't htmlspecialchars work in DOM context?

I need to insert an inscription in the "tag" containing double quotes ", but nothing changes. If you simply display a string on the screen and open the source code of the page, then they appear &qout;, but XML tags are not inserted in this form.

$testTag = $testXML->createElement('test-tag', htmlspecialchars($testString, ENT_XML1 | ENT_QUOTES));

I tried without flags, and pre-define a variable and shove everything there, and then call it in createElement. But it is inserted all the same with quotation marks.

The code:
<?php
$testString = 'проверка "тест"';
$testXML = new DOMDocument('1.0', 'utf-8');
$testXML->formatOutput = true;
$testXML->preserveWhiteSpace = false;

$testTag = $testXML->createElement('test-tag', htmlspecialchars($testString, ENT_XML1 | ENT_QUOTES));
$testXML->appendChild($testTag);
// МНОГО ДРУГИХ ВСТАВОК ТЕГОВ
$testXML->save('test.xml');


There should be in XML проверка &quot;тест&quot;

In general, dual use helped htmlspecialchars(). Source:
<?php
$testString = 'проверка "тест"';
$tshsc = htmlspecialchars($testString, ENT_XML1 | ENT_QUOTES);
$testXML = new DOMDocument('1.0', 'utf-8');
$testXML->formatOutput = true;
$testXML->preserveWhiteSpace = false;

$testTag = $testXML->createElement('test-tag', htmlspecialchars($tshsc, ENT_XML1 | ENT_QUOTES));
$testXML->appendChild($testTag);
// МНОГО ДРУГИХ ВСТАВОК ТЕГОВ
$testXML->save('test.xml');


I MADE A MISTAKE! It did not help. PHP converts & to &amp;and breaks everything. I did not find how to disable this conversion!

That is, in the end comes nonsense likeпроверка &amp;quot;тест&amp;quot;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Anton, 2020-06-30
@Fragster

To get a string, use DOMDocument::saveHTMLnot DOMDocument::saveXML. And htmlspecialchars is not needed there.

G
galaxy, 2020-06-30
@galaxy

What do you need to get? And what doesn't work?
Your code from the question (corrected $testXML->save('test.xml') -> print $testXML->saveXML()) works:

<?xml version="1.0" encoding="utf-8"?>
<test-tag>проверка "тест"</test-tag>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question