Link to home
Start Free TrialLog in
Avatar of Matthew B
Matthew BFlag for Canada

asked on

Array to JSON for cURL Post Field

I am trying to create an array, encode it with json_encode, and then use it as post fields for a curl request but i keep getting "items" invalid.

Here is my code:
$jsonPostArray = array(
                "tracking_number" => $tracking,
                "order_address_id" => $address,
                "shipping_provider" => $shipping,
                "items" => array(
                    "order_product_id" => $productId,
                    "quantity" => $quantity
                    )
                );

                $jsonPostData = json_encode($jsonPostArray,true);

Open in new window



and it outputs this below but the api im using returns an error and says items in invalid json? Im thinking it needs the [] brackets somewhere but cant tell how to generate that with PHP.

What am i doing wrong, is it how im building my array or how i am encoding it to json?

{
    "tracking_number": "88598020014",
    "order_address_id": "6863",
    "shipping_provider": "fedex",
    "items": {
        "order_product_id": "10890",
        "quantity": "3"
    }
}

Open in new window

Avatar of Nicolas Lecanu
Nicolas Lecanu
Flag of Guadeloupe image

Hi Matthew,

Just to a array of array for the []

$Taboftab = array($jsonPostArray);

this will add the []
Then if you want to do the api call,

function curlAPI($data, $url){
    try {
        $ch = curl_init();

        // Check if initialization had gone wrong*
        if ($ch === false) {
            throw new Exception('failed to initialize');
        }

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen('$data'))
        );
        $content = curl_exec($ch);
        $err = curl_error($ch);

        // Check the return value of curl_exec(), too
        if ($content === false) {
            throw new Exception(curl_error($ch), curl_errno($ch));
        }

        // Close curl handle
        curl_close($ch);
        $json_data = json_decode($content, true);

        return $json_data;
    } catch (Exception $e) {

        trigger_error(sprintf(
            'Curl failed with error #%d: %s',
            $e->getCode(), $e->getMessage()),
            E_USER_ERROR);

    }
}

Open in new window

Also, if you want to verify your json, this site do this  and tell you if your json format is good or not.
ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Matthew B

ASKER

Thanks chris, you were 100percent correct, it was expecting an array of arrays not an array of values.
No worries :)
I write the exact same thing first, but this is true that Chris right this more correctly.
@Nicolas - your code would convert the $jsonPostArray to an array. The problem was with the items property not being an array, so your code wouldn't have solved the problem :(
Chris,

$jsonPostArray is an array, you just encode this array in json after

$jsonPostArray = array(
    "tracking_number" => $tracking,
    "order_address_id" => $address,
    "shipping_provider" => $shipping,
    "items" => array(
        array(
            "order_product_id" => $productId,
            "quantity" => $quantity
        )
    ) 
);

Open in new window

and
$tab = array($jsonPostArray);

Open in new window


is the same thing butin fact  its more clean to do your code.
than you just have to do:

$jsonPostData = json_encode($jsonPostArray,true);

Open in new window

or with my code:
 json_encode($tab ,true);

Open in new window

Nicolas,

Sorry - but you're wrong !!

Take a look at this (your method):

$data = array(
    "tracking_number" => "123",
    "items" => array(
        "order_product_id" => "111",
        "quantity" => 1
    )
);

$tab = array($data);
var_dump( json_encode($tab) );

// Result:
[{
    "tracking_number": "123",
    "items": {
        "order_product_id": "111",
        "quantity": 1
    }
}]

Open in new window


Now take a look at this (my method):
$data = array(
    "tracking_number" => "123",
    "items" => array(
        array(
            "order_product_id" => "111",
            "quantity" => 1
        )
    )
);

var_dump( json_encode($data) );

//Result:
{
    "tracking_number": "123",
    "items": [{
        "order_product_id": "111",
        "quantity": 1
    }]
}

Open in new window

In your method, the whole object is converted to an array (the square brackets), which is wrong. In my method, the items property is wrapped in an array, which is correct. The data needs to be an object, with only the items as an array.
Chris,

Thank you I understand my error , its clear, sorry for my miss understood.

I have to be more carefull next time.

Thank you again for your explaination and  time Chris :D
No worries Nicolas :)