Coder
Coder

Reputation: 11

PHP: Get encoded html entities

I'm trying to get the html entities of a UTF-8 string,
Example: example.com/search?q=مرحبا

<?php
    echo htmlentities($_GET['q']);
?>

I got:

مرحبا0مرحبا

It's UTF-8 text not html entities, what I need is:

&#1605;&#1585;&#1581;&#1576;&#1575;

I have tried urldecode and htmlentities functions!

Upvotes: 1

Views: 219

Answers (2)

Saif Hamed
Saif Hamed

Reputation: 1094

I think you can solve it by getting the each char in the string and get its value.
From Mark Baker's answer and vartec's answer you can get:

<?php
    $chrArray = preg_split('//u',$_GET['q'], -1, PREG_SPLIT_NO_EMPTY);
    $htmlEntities = "";
    foreach ($chrArray as $chr) {
        $htmlEntities .= '&#'._uniord($chr).';';
    }
    echo $htmlEntities;
?>

I have not test it.

Upvotes: 1

user1122069
user1122069

Reputation: 1817

Add this code to the start of your file:

header('Content-Type: text/html; charset=utf-8');

The browser needs to know it is UTF-8. This tag also can go in the head section for formality.

<meta http-equiv="Content-type" content="text/html; charset=utf-8" />

Upvotes: 1

Related Questions