I am facing an issue regarding decoding special characters, specifically the ampersand (&) character.
SETUP
Frontend: Angular-6/Typescript
Backend: PHP/Laravel and Eloquent
Database: MySQL
Browser: Chrome
ISSUE
Using Javascript, I am sending data, in JSON format, using a simple text-based input form. When testing, I use "Me & You" as a test string. However, in the browser's Network tab, I notice that the JSON data takes the form of
book: {
title: "Me & You"
...
}
PHP/Laravel saves this string as it is in the database (Me & You
). Since I am also retrieving titles, even my frontend text field displays Me & You
as well.
REQUIRED BEHAVIOUR
It should save the string anyway it is (Me & You
) but before retrieving the entries, it should escape the special character so I receive Me & You
.
Any other suggestions would be appreciated as well. I just need to escape the ampersand character.
WHAT I HAVE ALREADY TRIED
I have tried the following to solve the issue, but to no avail:
- Before saving the Model using Laravel's
save
function, I usehtmlspecialchars_decode()
to decode the string, but it still gives meMe & You
both in the database and in the frontend.
$title= htmlspecialchars_decode($title);
- I tried
html_entity_decode
, but still no luck.
$title= html_entity_decode($title);
- I am also retrieving the titles, so I figured instead of decoding the string, I would let it save the string as it is in the table. But when I am retrieving the titles, I would decode them and then return them back to the fronend via a response.
foreach ($user->books as &$book) {
$book['title'] = urldecode(($book['title']));
}
But I still receive Me & You
. Note that here I am using references, because at first I thought that the foreach loop was creating a new temporary variable and not changing the original values.
- In javascript, I tried to use
encodeURIComponent()
book.title = encodeURIComponent(book.title);
which gives me Me%20%26%20You
.
In PHP, I then try to use urldecode()
, htmlspecialchars_decode()
etc. but I STILL get Me & You
.
Any help would be appreciated.
Thank you.