jose
jose

Reputation: 1562

json_encode error handling PHP OOP

On the server side (PHP) I use json_encode to encode the data sent with ajax request (javascript - extjs).

I want to handle the possible json_encode errors, if possible with PHP OOP.

So far I have the following code, but I'm having some difficulties (I'm inexperienced in php oop):

Class ValidateJson

<?php

class ValidateJson {

    private $errors = array();

   // public static function validaJson(){

    public function validaJson(){

        //Get the last JSON error.
        $jsonError = json_last_error();

        //If this happen.
        //if(is_null($decoded) && $jsonError == JSON_ERROR_NONE){
        //   $this->addJsonErrorMsg('Could not decode JSON!');
        //}


        switch ($jsonError) {
            case JSON_ERROR_DEPTH:
                    $this->addJsonErrorMsg('Maximum stack depth exceeded');
                break;
            case JSON_ERROR_STATE_MISMATCH:
                 $this->addJsonErrorMsg('Underflow or the modes mismatch');
                break;
            case JSON_ERROR_CTRL_CHAR:
                 $this->addJsonErrorMsg('Unexpected control character found');
                break;
            case JSON_ERROR_SYNTAX:
                 $this->addJsonErrorMsg('Syntax error, malformed JSON');
                break;
            case JSON_ERROR_UTF8:
                 $this->addJsonErrorMsg('Malformed UTF-8 characters, possibly incorrectly encoded');
                break;
            default:
                 $this->addJsonErrorMsg(' Unknown error');
                break;
        }
    }

    private function addJsonErrorMsg($error_message){
        $this->errors[] = $error_message;
    }

    public function outJsonError(){
        return $this->errors;
    }

    // ?????
    //     if($jsonError != 0){
    //         throw "JSON Parse Error: " + untyped __call__("json_last_error_msg");
    //
    //    }
}

?>

Query and output:

<?php

require('conect.php');
$action = $_REQUEST['action'];

switch($action){

  case "create":{

    $records = $_POST['records'];
    $data = json_decode(stripslashes($records));

    require_once('validate_json.php');
    $valida_json = new ValidateJson();
    $valida_json->validaJson();

   //  $errosJson = $valida_json->outJsonError();
   //  echo $errors; exit; //return string 'Array'

    if(json_last_error() == JSON_ERROR_NONE){

        $cars = $data->{'cars'};

        if ($_SERVER["REQUEST_METHOD"] == "POST") {

            $sqlQuery = "INSERT INTO the_cars (cars) VALUES (?)";

            if($statement = $con->prepare($sqlQuery)){
                $statement->bind_param("s", $cars);
                $statement->execute();
                $success= true;
            }else{
                $erro = $con->error;
                $success = false;
            }

            echo json_encode(array(
                "success" => $sucess,
                'errors'=> $erro
            ));

            $statement->close();
            $conexao->close();

            break;
        }

   }else{

        $errorsJson = $valida_json->outJsonError();
        $success = false;

         echo json_encode(array(
                "success" => $sucess,
                'errorsjson'=> $errorsJson
         ));
    }
}
?>

Upvotes: 1

Views: 2462

Answers (2)

bouguima
bouguima

Reputation: 156

i get this issue "Malformed UTF-8 characters, possibly incorrectly encoded" when trying to get json_encode of an array and here is the solution for it

 function latin1_to_utf8($dat)
    {
     if (is_string($dat))
        return utf8_encode($dat);
     if (!is_array($dat))
        return $dat;
     $ret = array();
     foreach ($dat as $i => $d)
        $ret[$i] = array_utf8_encode($d);
     return $ret;
    }
    function array_utf8_encode($dat)
    {
         if (is_string($dat))
             return utf8_encode($dat);
        if (!is_array($dat))
          return $dat;
      $ret = array();
      foreach ($dat as $i => $d)
          $ret[$i] = array_utf8_encode($d);
      return $ret;
    }

Upvotes: 3

aknosis
aknosis

Reputation: 4338

Try removing static from public static function validaJson(){.

By defining validaJson as static you do not have a working instance of validaJson ($this) to work with.

Also inside of validaJson you have is_null($decoded) which won't work because the variable $decoded isn't inside of that function anywhere.

See: http://php.net/manual/en/language.oop5.static.php

Upvotes: 2

Related Questions