-2

I am trying to get superscript working in php. I am replacing the tag with a superscript digit as shown below in the script. The output I get is O² instead of getting . How do I fix this issue?

<?php 
$a = "O<sup>2</sup>";
$a = str_replace("<sup>2</sup>", "²", $a);
...
...
?>

I am adding the value of $a manually in the script here but I am receiving the value as a POST $_SERVER["REQUEST_METHOD"] == "POST" from external application. Basically:

    $a = htmlspecialchars_decode($POST['myValue'], ENT_QUOTES);
    $a = utf8_decode($a);
    $a = str_replace("<sup>2</sup>", "²", $a);

I even tried adding php header('Content-type: text/plain; charset=utf-8'); in the header of the php script but still no luck.

Saif
  • 97
  • 1
  • This might be a [UTF-8 All the way through problem](https://stackoverflow.com/questions/279170/utf-8-all-the-way-through) – RiggsFolly Sep 13 '21 at 11:35
  • Anyone looking for the answer, the answer is to add utf-decode. Such that ```$a= str_replace("2", utf8_decode("²"), $a);``` – Saif Sep 13 '21 at 12:55

1 Answers1

0

You have to set UTF-8 charset somewhere in your web page.

This example will display :

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Super</title>
</head>
<body>
O²
</body>
</html>

But if I remove <meta charset="UTF-8"> it will show O² in the browser :)

jawira
  • 3,668
  • 2
  • 17
  • 27
  • I tried adding ```header('Content-Type: text/html; charset=UTF-8');``` in php but still I am facing the same issue. I know it works in HTML perfectly, but in php it is causing this issue. – Saif Sep 13 '21 at 11:43
  • You can set the charset using an http header. Put this at the begining of your script `header('Content-Type: text/html; charset=utf-8');` – jawira Sep 13 '21 at 11:49
  • You an also set charset inside `php.ini`. Add this `default_charset = "UTF-8"` – jawira Sep 13 '21 at 11:50