search

Home  >  Q&A  >  body text

json_encode returns null on valid JSON string

<p>I'm using PHP's json_decode function to parse a JSON string created by JavaScript's JSON.stringify; </p><p>JSON appears to be valid: </p><p>JSON String: </p><p><br /></p> <pre class="brush:php;toolbar:false;">"{"m_user_name":"test","m_user_phone":" 60 12-384 7961","m_user_city":"Kuala Lumpur","m_user_linkedin ":"example@gmail.com","m_user_g_plus":"example@gmail.com"}"</pre> <p>JSON final error message: "Syntax error"</p><p>Okay, if I paste the string directly into json_decode it works. I'm sending a string via ajax via a form_data object and then trying to decode the post variable. </p><p>The following is the code for the ajax request:</p><p><br /></p> <pre class="brush:php;toolbar:false;">$.ajax({ type: "POST", url: ajaxurl, data: formdata, cache: false, contentType: false, processData: false, beforeSend: function () { toggle_loading_spinner(); }, success: function (data) { console.log(data); toggle_loading_spinner(); }, });</pre> <p>I tried using preg_replace('/[x00-x1Fx80-xFF]/', '', $JSON_STRING) to remove the unwanted symbols, but I got the same error. </p>
P粉176980522P粉176980522544 days ago557

reply all(1)I'll reply

  • P粉814160988

    P粉8141609882023-07-29 14:53:06

    json_decode() function only works with strings encoded in UTF-8. The input may be in a different encoding. After removing the unwanted characters, try converting the encoding to UTF-8. Here are references on how to do the conversion:

    https://www.php.net/manual/en/function.mb-convert-encoding.php

    reply
    0
  • Cancelreply