Wednesday, November 28, 2018

Converting a string containing a UTF-8 character in PHP.

This article will show user how to convert a string containing a UTF-8 character in PHP.

When using PHP to integrate NetSuite with other application, user might encounter an error if they submit a request containing a UTF-8 character. The code below will explain how to get the error.
  
  $otherName = "Test - Name°"; // Free-Form text 
  $customStringField = new nsComplexObject("StringCustomFieldRef");
  $customStringField->setFields(array("value" => $otherName, "internalId" => "custrecord47"));
  $customRecordFields = array("recType" => $recordTypeRef,  'customFieldList'  => array($customStringField)); 
  $customRecord = new nsComplexObject('CustomRecord');
  $customRecord->setFields($customRecordFields);

If this code is executed it will throw an error: 'Uncaught SoapFault exception: [Client] SOAP-ERROR: Encoding: string 'Test - Name\xb0...' is not a valid utf-8 string in C:\Program Files (x86)\EasyPHP-5.3.9\www\PHP_Toolkit\PHPtoolkit.php:1638 Stack trace: #0'

To eliminate the error from appearing we need to encode the string using the function utf8_encode.
This function encodes the string data to UTF-8, and returns the encoded version. UTF-8 is a standard mechanism used by Unicode for encoding wide character values into a byte stream.

The PHP code will now look like the code below:

  $otherName = utf8_encode("Test - Name°"); 
  $customStringField = new nsComplexObject("StringCustomFieldRef");
  $customStringField->setFields(array("value" => $otherName, "internalId" => "custrecord47"));
  $customRecordFields = array("recType" => $recordTypeRef,  'customFieldList'  => array($customStringField)); 
  $customRecord = new nsComplexObject('CustomRecord');
  $customRecord->setFields($customRecordFields);

No comments:

Post a Comment