ian
ian

Reputation: 12335

converting & to & for XML in PHP

I am building a XML RSS for my page. And running into this error:

error on line 39 at column 46: xmlParseEntityRef: no name

Apparently this is because I cant have & in XML... Which I do in my last field row...

What is the best way to clean all my $row['field']'s in PHP so that &'s turn into &

Upvotes: 4

Views: 17323

Answers (5)

ganji
ganji

Reputation: 854

Convert Reserved XML characters to Entities

 function xml_convert($str, $protect_all = FALSE)
{
    $temp = '__TEMP_AMPERSANDS__';

    // Replace entities to temporary markers so that
    // ampersands won't get messed up
    $str = preg_replace("/&#(\d+);/", "$temp\\1;", $str);

    if ($protect_all === TRUE)
    {
        $str = preg_replace("/&(\w+);/",  "$temp\\1;", $str);
    }

    $str = str_replace(array("&","<",">","\"", "'", "-"),
                        array("&amp;", "&lt;", "&gt;", "&quot;", "&apos;", "&#45;"),
                        $str);

    // Decode the temp markers back to entities
    $str = preg_replace("/$temp(\d+);/","&#\\1;",$str);

    if ($protect_all === TRUE)
    {
        $str = preg_replace("/$temp(\w+);/","&\\1;", $str);
    }

    return $str;
}

Upvotes: 1

Aduljr
Aduljr

Reputation: 214

Really should look in the dom xml functions in php. Its a bit of work to figure out, but you avoid problems like this.

Upvotes: 2

Petrogad
Petrogad

Reputation: 4423

Use

html_entity_decode($row['field']);

This will take and revert back to the & from & also if you have &npsb; it will change that to a space.

http://us.php.net/html_entity_decode

Cheers

Upvotes: 0

Gumbo
Gumbo

Reputation: 655609

Use htmlspecialchars to encode just the HTML special characters &, <, >, " and optionally ' (see second parameter $quote_style).

Upvotes: 10

&#211;lafur Waage
&#211;lafur Waage

Reputation: 70001

It's called htmlentities() and html_entity_decode()

Upvotes: 2

Related Questions