title: "Malformed UTF-8 characters" error when trying to json_encode and array that holds some encrypted values
body: <p>I need to send some JSON data to an API endpoint that requires parts of the request to be encrypted. I have a public key that was supplied to me by the API provider. Here's the relevant piece of code:</p>
  
  <pre class="lang-php prettyprint-override"><code>$key = "-----BEGIN PUBLIC KEY-----
  XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  -----END PUBLIC KEY-----";
  
  openssl_public_encrypt('my_username', $username, openssl_pkey_get_public($key));
  openssl_public_encrypt('my_pa55w0rd', $password, openssl_pkey_get_public($key));
  
  $client = new GuzzleHttp\Client();
  $result = $client-&gt;post(
      'https://api.domain.com/endpoint',
      [
          'headers' =&gt; [
              'Authorization' =&gt; 'Bearer ' . $bearerToken,
              'Content-Type' =&gt; 'application/json',
          ],
          'json' =&gt; [
              'username' =&gt; $username,
              'pasword' =&gt; $password,
              'unencrypted_key' =&gt; 'an unencrypted value,
          ]
      ]
  );
  </code></pre>
  
  <p>The code snippet above gives me an <code>json_encode error: Malformed UTF-8 characters, possibly incorrectly encoded</code> error. When doing a <code>echo $username;</code> I see that the string outputted has a bunch of malformed characters:
  <a href="https://i.stack.imgur.com/8DPjr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8DPjr.png" alt="malformed encrypted string"></a></p>
  
  <p>I'm not sure what I'm doing wrong or if there's some other approach I should take to encrypting the values before it gets json encoded.</p>
  
  <p><strong>NOTE:</strong> Although I am not using the <code>json_encode</code> function in my code above, I believe the guzzle HTTP library <code>json_encode</code>s the array before sending out the request.</p>