Posted on Friday 7th of December 2007 at 06:11 in Web Development

HTML character encoding with PHP made easy

While digging around in my development area I found a handy PHP function that has probably been overlooked by many - so I thought I'd document it quickly.

Supposing you've got a string (called $mystring) that has a lot of unusual characters in it, it'd be helpful to convert them all to their HTML entities. I stumbled across this when dealing with forms where users would enter content in their native format (Croatian, Czech, etc) and it needed to be HTML encoded for database reasons. Clearly doing a character-by-character str_replace would be problematic so you need a way to convert them all.

$mystring = mb_convert_encoding($mystring, 'HTML-ENTITIES', 'UTF-8');

So we have $mystring that has a lot of nasty characters in it, by running it through the above function it converts all UTF-8 characters into their HTML entities. Which can be quite helpful.

 

Enjoy this article? Why not subscribe to the full RSS feed?

Add Your Comments








Comments

Showing most recent 1 of 1 comments

Why would you want to HTML encode the data in your database? That just causes more problems later down the road.... If you wish to use the data in an XML or PDF document...

Far better to store you data in the database in its native characters... Obviously you would still make the data safe by means of something like mysql_real_escape_string().

mb_convert_encoding($mystring, ’HTML-ENTITIES’, ’UTF-8’) would do a lot more than make the string database safe. Would it in fact do that? Would it deal with single quotes?

I would suggest that this function is used when you output your data to an HTML page. But even then if you send a UTF-8 header to the browser it will do all the magic for you and display the characters correctly.

Subscribe to the RSS Feed

Stay up to date with Seopher.com by subscribing to the RSS feed, either in your browser or subscribe via email using the form below

Updates by Email

By subscribing by email you’re also subscribing to the Seopher.com newsletter; a periodical email outlining new reviews, competitions and other subscriber-only content

  • 125x125 banner only $50 pcm
  • make money online with t3leads
Want to give your product/website exposure?

Paying for a featured review is a great way to give your product, service or website exposure. For as little as $50 you can have a full review on the site forever.

Advertising Bundle! Review + Banner = $70

To kick start the new improved Seopher.com, buy a review and get a 125x125 advert half price. Your banner gets displayed on over 450 pages for a full month.