Eddie
Eddie

Reputation: 83

XML, HTML, PHP, Write an elegant, easy to read string with quotes

I use HTML and PHP to parse HTML content and write to XML file. I want to write this first XML header :

<?xml version="1.0" encoding="UTF-8"?>

I use the following code to write the above:

fwrite ($myfile, htmldec("&lt;?xml version=&#34;1.0&#34; encoding=&quot;UTF-8&quot;?&gt;"));

where htmldec is a function to decode using htmlspecialchars_decode.

It works ok, but not too legible. Is there a simpler way to represent the string so that it is easier to read for humans?

Upvotes: 2

Views: 170

Answers (1)

GolezTrol
GolezTrol

Reputation: 116100

If you use simple strings, you don't have to encode HTML characters like < and >. You only need to escape the quote, so your statement can be written as:

fwrite ($myfile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

Additionally, PHP supports single quote strings and double quote strings. Single quotes don't need to be escaped in double quote strings and vice versa, so you could also write:

fwrite ($myfile, '<?xml version="1.0" encoding="UTF-8"?>');

In your case that is about as easy as it gets.

However, sometimes, you will have larger strings with a mix of quotes and other symbols. Instead of escaping the necessary characters, you can use HEREDOC syntax:

fwrite ($myfile, <<<XML
<?xml version="1.0" encoding="UTF-8"?>
XML
);

Or use a variable inbetween to extract it from the function call:

$xmlHeader = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
XML;

fwrite ($myfile, $xmlHeader);

If you use PHP 5.3 or up (and I assume you do, otherwise it's seriously time to update), you can use the similar NOWDOC syntax.

There is a slight difference between these string types. Double quote strings and HEREDOC strings can contains variables, so the result of "Hello $world." will contain the value of the variable $world. Single quoted strings and NOWDOC strings don't do this parsing. Please check the full article about strings to read about all the details and differences of these string types.

Upvotes: 4

Related Questions