How do I code a string in json with php?

1

hi all I need is to encode a string that is in json format

in python is something like this:

def queue(self, url, api_user, api_pass, api_version):
    args = urllib.urlencode({'cmd': 'api_queue_sms', 'username': api_user, 'password': api_pass, 'content': self.contenido, 'destination': self.destino, 'api_version': api_version})

but I need to pass it to php what is done is this:

function queue($url, $api_user, $api_pass, $api_version){
        $args = urlencode('cmd': 'api_queue_sms', 'username': $api_user, 'password': $api_pass, 'content': $this->contenido, 'destination':  $this->destino, 'api_version': $api_version);

but he does not recognize me ":" I guess I need something to tell him it's json

I hope your help thanks

    
asked by ingswsm 03.04.2017 в 17:47
source

2 answers

0

You could solve it in the following way:

  • Create a array associative with the information.
  • Encode array to JSON using the function json_encode
  • Finally encode the JSON to URL using the function urlencode

Example:

function queue($url, $api_user, $api_pass, $api_version) {
    $info = array(
      'cmd'=> 'api_queue_sms',
      'username'=> $api_user,
      'password'=> $api_pass,
      'content'=> $this->contenido,
      'destination'=> $this->destino,
      'api_version'=> $api_version
    );
    $args = urlencode(json_encode($info));
    /** bla bla bla */

Demo

    
answered by 03.04.2017 / 18:10
source
1

the urlencode function is passed by a string and those not what you're going through I guess what you want to do is something like this:

   $json="{'nombre':'Omar','apellido':'Miranda'}";
   $codificado=urlencode($json);

So you already have the json encoded and then to retrieve it you just have to do the following:

  $json=urldecode($codificado);

I hope you find it useful.

    
answered by 03.04.2017 в 18:06