1

I have JSON that has been saved in a text box on my site to a database below.

{"@type":"GOOOGLE.COM","@id":"GOOGLE","url":"GOOGLE","inLanguage":"en-US","name":"dfghjk | Bloomberg Professional Services","isPartOf":{"@id":"GOOGLE,"datePublished":"2020-02-11T21:51:45+00:00","dateModified":"2020-02-11T21:51:45+00:00"}]}

I want to convert it to look properly in PHP as so:

{"@type":"GOOOGLE.COM","@id":"GOOGLE","url":"GOOGLE","inLanguage":"en-US","name":"dfghjk | Bloomberg Professional Services","isPartOf":{"@id":"GOOGLE,"datePublished":"2020-02-11T21:51:45+00:00","dateModified":"2020-02-11T21:51:45+00:00"}]}

I tried doing a json_encode but its not working. How do i convert that string with all those escape quotes etc to a normal json string in PHP?

I tried as so:

  $str = "{"@type":"GOOOGLE.COM","@id":"GOOGLE","url":"GOOGLE","inLanguage":"en-US","name":"dfghjk | Bloomberg Professional Services","isPartOf":{"@id":"GOOGLE,"datePublished":"2020-02-11T21:51:45+00:00","dateModified":"2020-02-11T21:51:45+00:00"}]}"
  $data = json_encode($str, true);  
  return $data; 
1
  • Even after decoding the HTML entities, there are still a couple of syntax errors in there - the nested "GOOGLE value isn't quoted properly, and there's a spare ] at the end. It'll need fixing manually. Commented Feb 12, 2020 at 15:59

1 Answer 1

2

You need to decode HTML entities back into characters:

https://www.php.net/manual/en/function.htmlspecialchars-decode.php

  $json = htmlspecialchars_decode($str, true);  // valid json string
  $data = json_decode($json); // convert json to php data structure
  return $data;
Sign up to request clarification or add additional context in comments.

6 Comments

didnt seem to work, in the end it comes out to null and using the debugger i see it doesnt change
looks like $json = htmlspecialchars_decode($str, true); should just be $json = htmlspecialchars_decode($str);
also, the provided JSON string is not a valid JSON. A few quotes are misplaced
Gotcha,is there a way i can remove the outside quotes as well and replace them with single? "{"@type":"GOOOGLE.COM","@id":"GOOGLE","url":"GOOGLE","inLanguage":"en-US","name":"dfghjk | Bloomberg Professional Services","isPartOf":{"@id":"GOOGLE,"datePublished":"2020-02-11T21:51:45+00:00","dateModified":"2020-02-11T21:51:45+00:00"}]}"
JSON standard uses double-quotes for strings.If you convert double quotes with singe, that will break the json even further. I do not think there is a one-fits-all solution to repair broken JSON.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.