hi all,

I have a php script that saves what the user types in into a text file using fwrite, and displays it on another page using file_get_contents.

When putting in a pound sign (£), it saves the following to the text file:

£

Any idea how I can stop this from happening and instead get the pound sign working properly?

Max.

Dani AI

Generated

Quick diagnostic summary: this is an encoding mismatch. The British pound sign (U+00A3) is encoded in UTF-8 as the two bytes 0xC2 0xA3; if those bytes are interpreted as ISO-8859-1 / Windows-1252 the 0xC2 byte is shown as an "A with circumflex" and 0xA3 as the pound character. That pattern explains the extra-character symptom. was correct to suspect UTF-8 issues.

Keep encodings consistent end-to-end. Declare UTF-8 on pages and forms, send UTF-8 headers, and write UTF-8 bytes to disk. Example declarations:

<meta charset="utf-8">
<form accept-charset="UTF-8" ...>
header("Content-Type: text/html; charset=utf-8");

On the PHP side, detect and convert incoming text before writing. A safe approach:

$enc = mb_detect_encoding($input, 'UTF-8, ISO-8859-1, Windows-1252', true);
if ($enc !== 'UTF-8') $input = mb_convert_encoding($input, 'UTF-8', $enc);
if (substr($input,0,3) === "\xEF\xBB\xBF") $input = substr($input,3); // strip BOM
file_put_contents('notes.txt', $input);

Quick troubleshooting tips: inspect raw bytes (hexdump or PHP's bin2hex). If the file shows "c2a3" the pound was stored as UTF-8; if it shows "a3" it was stored as single-byte Latin-1. Avoid blindly running utf8_encode on already-UTF-8 text (that causes double-encoding). 's entity-replacement is a valid HTML display workaround (stores "&pound;" text), but enforcing a single encoding (preferably UTF-8 without BOM) is the correct fix for truly preserving the character in the text file.

Recommended Answers

All 3 Replies

<?php
$input = str_replace("£", "&pound;", $input);
?>

where $input is the string you are entering into a text file.

Kyle

iv tried that but cant get any changes working. its quite a complex problem and I have tried many possible solutions... if anybody else has had the same thing that would be best.

I think its an encoding charset discrepency?

UTF-8 encoding
html charset
the GBP pound sign gets 2 bytes in utf8 utf16 its not one of the lower 127 ascii codes that gets directly translated
the page that reads the stored data file needs to be charset UTF-8,
logically aware of the answer, my phone does not have my stored links on it so I cant post the relevant link
(anti boredom browsing)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.