Monday, February 7, 2011

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 &

  • It's called htmlentities() and html_entity_decode()

    Jason Musgrove : XML does not share all of the same *named* entities as HTML - having only 5 predefined entities (amp, lt, gt, quot, and apos). Unless the XML document has a DTD attached to it that includes all of the HTML named entities, using htmlentities(), which converts could convert some characters into entities that an XML parser is not required to support.
    ian : So what is best to use then?
    Jason Musgrove : @ian: Given Gumbo's description of `htmlspecialcharacters()`, I would go with that (as it only touches the 5 characters with predefined entities in XML)
  • Use htmlspecialchars to encode just the HTML special characters &, <, >, " and optionally ' (see second parameter $quote_style).

    From Gumbo
  • 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

    ian : Not sure why I would want to revert... This is for a RSS feed.
    From Frederico
  • Really should look in the dom xml functions in php. Its a bit of work to figure out, but you avoid problems like this.

    ian : How so? Point me to something and I will figure it out.
    From Aduljr

0 comments:

Post a Comment