i want to take data of username(david) from this Json , I saw the similar question i try more than 100 times but i can not , I need exact answer if it's possible.
thanks in advance
{
"related_assets": [],
"orders": [],
"auctions": [],
"supports_wyvern": true,
"top_ownerships": [
{
"owner": {
"user": {
"username": "david"
},
"",
"address": "",
"config": ""
},
"quantity": "1"
}
],
"ownership": null,
"highest_buyer_commitment": null
}
and i coded as below :
<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
//the second parameter turns the objects into an array
$decodedData = json_encode($response, true);
$owner = $decodedData['top_ownerships'][0]['owner'];
$username = $owner['user']['username'];
echo $username;
}
the output is "
please help thanks
your code is completely current! and it works like charm!
but you made a very ambiguous mistake in your JSON code
you're using this ” instead of " (double quotes) there "david” <----
they exactly look the same!
and also you missed {} in the beginning and end of your JSON code
checkout your json code here it's the best tool for this
<?php
$code = '{
"top_ownerships": [{
"owner": {
"user": {
"username": "david"
},
"profile_img_url": "",
"address": "",
"config": ""
},
"quantity": "1"
}]
}';
$decodedData = json_decode($code, true);
$owner = $decodedData['top_ownerships'][0]['owner'];
$username = $owner['user']['username'];
echo $username;
?>
To start with, it's important you understand how to access json fields and key php;
Assuming the above values are stored in a file known as data.json, we can extract the values like this:
$data = file_get_contents('data.json');
//the second parameter turns the objects into an array
$decodedData = json_decode($data, true);
$owner = $decodedData['top_ownerships'][0]['owner'];
$username = $owner['user']['username'];
//echo $username
The above would work if your json file or data is properly encoded.
first you have to store your JSON into a variable, lets call it $json.
$jsonArray = json_decode($json,true);
And set your key name, the key you want from your JSON.
$key = "owner";
$owner= $jsonArray[$key];
You also can read like an object:
$owner= $jsonObj->$key;
Try
$object = json_decode('{"owner": {"user": {"username": "david”},"profile_img_url": "","address": "","config": ""},"quantity": "1"}')
echo $object->owner->user->username
This will make the JSON an object that you can access by using the -> accessor
I am working with an API at the moment that will only return 200 results at a time, so I am trying to run some code that works out if there is more data to fetch based on whether or not the results have a offsetCursor param in them as this tells me that that there are more results to get, this offsetCursor is then sent a param in the next request, the next set of results come back and if there is an offsetCursor param then we make another request.
What I am wanting to do is push the results of each request into a an array, here is my attempt,
function get_cars($url, $token)
{
$cars = [];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Content-Type: application/x-www-form-urlencoded",
"Authorization: Bearer " . $token
)
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if($err) {
return false;
} else {
$results = json_decode($response, TRUE);
//die(print_r($results));
$cars[] = $results['_embedded']['results'];
if(isset($results['cursorOffset']))
{
//die($url.'&cursor_offset='.$results['cursorOffset']);
get_cars('https://abcdefg.co.uk/service/search1/advert?size=5&cursor_offset='.$results['cursorOffset'], $token);
//array_push($cars, $results['_embedded']['results']);
}
}
die(print_r($cars));
}
I assume I am doing the polling of the api correct in so mush as that if there is a cursor offet then I just call the function from within itself? But I am struggling to create an array from the results that isnt just an array within and array like this,
[
[result from call],
[resul from call 2]
]
what I really want is result from call1 right through to call n be all within the same sequential array.
using a do+while loop, you'll have only 1 instance of cars variable, that would work.
Since you're using recursion, when you call get_cars inside get_cars, you have 2 instances of cars variable, one per get_cars call.
IMHO, using a loop is better in your case.
But if you still want to use recursion, you should use the result of get_cars call, something like this:
if(isset($results['cursorOffset']))
{
//die($url.'&cursor_offset='.$results['cursorOffset']);
$newcars = get_cars('https://abcdefg.co.uk/service/search1/advert?size=5&cursor_offset='.$results['cursorOffset'], $token);
$cars = array_merge($cars, $newcars);
//array_push($cars, $results['_embedded']['results']);
}
(and get_cars should return $cars, instead of printing it with print_r)
Edit: here is an example of, untested, code with a while loop (no need for do+while here)
<?php
function get_cars($baseUrl, $token)
{
$cars = [];
// set default url to call (1st call)
$url = $baseUrl;
while (!empty($url))
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Content-Type: application/x-www-form-urlencoded",
"Authorization: Bearer " . $token
)
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if($err)
{
// it was "return false" in your code
// what if it's the 3rd call that fails ?
// - "return $cars" will return cars from call 1 and 2 (which are OK)
// - "return false" will return no car (but call 1 and 2 were OK !!)
return $cars;
}
$results = json_decode($response, TRUE);
$cars[] = $results['_embedded']['results'];
if(isset($results['cursorOffset']))
{
// next call will be using this url
$url = $baseUrl . '&cursor_offset='.$results['cursorOffset'];
// DONT DO THE FOLLOWING (concatenating with $url, $url = $url . 'xxx')
// you will end up with url like 'http://example.com/path/to/service?cursor_offset=xxx&cursor_offset==yyy&cursor_offset==zzz'
// $url = $url . '&cursor_offset='.$results['cursorOffset'];
}
else
{
$url = null;
}
}
return $cars;
}
I recently work with kraken.io API and I'm trying to integrate this API wuth my PHP CodeIgniter framework. So I followed the documentation but I got stuck when I used curl
This is my source code below ..
require_once(APPPATH.'libraries/kraken-php-master/Kraken.php');
$kraken = new Kraken("SOME_KEY", "SOME_SECRET");
$params = array(
"file" => base_url()."include/".$dataIn['logo'],
"wait" => true
);
$dataj='{"auth":{"api_key": "SOME_KEY", "api_secret": "SOME_SECRET"},"file":'.base_url()."include/".$dataIn['logo'].',wait":true}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.kraken.io/v1/upload");
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataj);
$response = curl_exec($ch);
curl_close($ch);
$data = $kraken->upload($params);
print_r($response);exit();
And I got this result
"{"success":false,"message":"Incoming request body does not contain a valid JSON object"}1"
So can anyone please help me,
And thanks in advance,
DONT POST YOUR API_KEY AND API_SECRET
The error message is quite clear, your json object is not valid. For instance this would be a valid JSON object for your request:
{
"auth": {
"api_key": "SOME",
"api_secret": "SECRET"
},
"file": "somefile.txt",
"wait": true
}
In your php code you are setting up a $params array but then you don't use it. Try this:
$dataj='{"auth":{"api_key": "SOME_KEY", "api_secret": "SOME_SECRET"},"file":"' . $params["file"]. '", "wait":true}';
You can validate your JSON HERE
You should use json_encode function to generate your JSON data
$dataj = json_encode([
"auth" => [
"api_key" => "API_KEY",
"api_secret" => "API_SECRET"
],
"file" => base_url() . "include/" . $dataIn['logo'],
"wait" => true
]);
EDIT:
Here is an example from https://kraken.io/docs/upload-url so you don't need to use curl
require_once("Kraken.php");
$kraken = new Kraken("your-api-key", "your-api-secret");
$params = array(
"file" => "/path/to/image/file.jpg",
"wait" => true
);
$data = $kraken->upload($params);
if ($data["success"]) {
echo "Success. Optimized image URL: " . $data["kraked_url"];
} else {
echo "Fail. Error message: " . $data["message"];
}
we have been working with 3d cart rest response which we have successfully get here is my code.file name example.php which located in my wamp server
<?php
$host = 'https://apirest.3dcart.com';
$version = 1;
$service = 'Orders';
$secureUrl = 'https://xxxxyyyyy.3dcart.net'; // Secure URL is set in Settings->General->StoreSettings
$privateKey = 'xxxxxxxxxxxxxxxx'; // Private key is obtained when registering your app at http://devportal.3dcart.com
$token = 'xxxxxxxxxxxxx'; // The token is generated when a customer authorizes your app
// initialize cURL session
$ch = curl_init($host . '/3dCartWebAPI/v' . $version . '/' . $service);
// set headers
$httpHeader = array(
'Content-Type: application/json;charset=UTF-8',
'Accept: application/json',
'SecureUrl: ' . $secureUrl,
'PrivateKey: ' . $privateKey,
'Token: ' . $token,
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
// [ ... addtional cURL options as needed ... ]
$response = curl_exec($ch);
if ($response === false) {
$response = curl_error($ch);
}
curl_close($ch);
we have an access file on a browser using this URL http://localhost/social/example.php get a response in JSON like this without JSON encoded. but I want array this response so we can write CSV file.i have many try to google but no more luck for appropriate solution.thanks in advance.
[{"InvoiceNumberPrefix":"AB-","InvoiceNumber":1000,"OrderID":1,"CustomerID":1,"OrderDate":"2014-01-10T12:44:37","OrderStatusID":1,"LastUpdate":"0001-01-01T00:00:00","UserID":"","SalesPerson":"","ContinueURL":"http://71745179439.3dcart.net/continue_order.asp?orderkey=tl31S22wts7B0hF1","BillingFirstName":"John","BillingLastName":"Doe","BillingCompany":"","BillingAddress":"123 Street","BillingAddress2":"","BillingCity":"Coral Springs","BillingState":"FL","BillingZipCode":"33065","BillingCountry":"US","BillingPhoneNumber":"800-828-6650","BillingEmail":"test#3dcart.com","BillingPaymentMethod":"Online Credit Card","BillingOnLinePayment":true,"BillingPaymentMethodID":"1","ShipmentList":[{"ShipmentID":0,"ShipmentLastUpdate":"0001-01-01T00:00:00","ShipmentBoxes":1,"ShipmentInternalComment":"Sample Order from 3dcart","ShipmentOrderStatus":1,"ShipmentAddress":"123 Street","ShipmentAddress2":"","ShipmentAlias":"","ShipmentCity":"Coral Springs","ShipmentCompany":"","ShipmentCost":0.0,"ShipmentCountry":"US","ShipmentEmail":"","ShipmentFirstName":"Test","ShipmentLastName":"Test","ShipmentMethodID":0,"ShipmentMethodName":"Free Shipping","ShipmentShippedDate":"","ShipmentPhone":"800-828-6650","ShipmentState":"FL","ShipmentZipCode":"33065","ShipmentTax":0.0,"ShipmentWeight":1.0,"ShipmentTrackingCode":"","ShipmentUserID":"","ShipmentNumber":1,"ShipmentAddressTypeID":0}],"OrderItemList":[{"CatalogID":3,"ItemIndexID":1,"ItemID":"1003K","ItemShipmentID":0,"ItemQuantity":1.0,"ItemWarehouseID":0,"ItemDescription":"Tote Bag
Color: Khaki","ItemUnitPrice":1.0,"ItemWeight":3.0,"ItemOptionPrice":0.0,"ItemAdditionalField1":"","ItemAdditionalField2":"","ItemAdditionalField3":"","ItemPageAdded":"Tote-Bag_p_3.html","ItemDateAdded":"2009-06-22T12:05:07","ItemUnitCost":0.0,"ItemUnitStock":5.0,"ItemOptions":",1","ItemCatalogIDOptions":"","ItemSerial":"","ItemImage1":"http://71745179439.3dcart.net/assets/images/default/handbag.jpg","ItemImage2":"http://71745179439.3dcart.net/assets/images/default/handbag.jpg","ItemImage3":"http://71745179439.3dcart.net/assets/images/default/handbag.jpg","ItemImage4":"http://71745179439.3dcart.net/assets/images/default/handbag.jpg","ItemWarehouseLocation":"","ItemWarehouseBin":"","ItemWarehouseAisle":"","ItemWarehouseCustom":""}],"PromotionList":[],"OrderDiscount":0.0,"SalesTax":0.0,"SalesTax2":0.0,"SalesTax3":0.0,"OrderAmount":1.0,"AffiliateCommission":0.0,"TransactionList":[],"CardType":"","CardNumber":"","CardName":"John Doe","CardExpirationMonth":"","CardExpirationYear":"","CardIssueNumber":"","CardStartMonth":"","CardStartYear":"","CardAddress":"","CardVerification":"","RewardPoints":"1","QuestionList":[],"Referer":"http://www.google.com","IP":"","CustomerComments":"Sample Order from 3dcart","InternalComments":"","ExternalComments":""}]
You can use json_decode php function : http://php.net/manual/fr/function.json-decode.php
On your code :
<?php
$host = 'https://apirest.3dcart.com';
$version = 1;
$service = 'Orders';
$secureUrl = 'https://xxxxyyyyy.3dcart.net'; // Secure URL is set in Settings->General->StoreSettings
$privateKey = 'xxxxxxxxxxxxxxxx'; // Private key is obtained when registering your app at http://devportal.3dcart.com
$token = 'xxxxxxxxxxxxx'; // The token is generated when a customer authorizes your app
// initialize cURL session
$ch = curl_init($host . '/3dCartWebAPI/v' . $version . '/' . $service);
// set headers
$httpHeader = array(
'Content-Type: application/json;charset=UTF-8',
'Accept: application/json',
'SecureUrl: ' . $secureUrl,
'PrivateKey: ' . $privateKey,
'Token: ' . $token,
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
// [ ... addtional cURL options as needed ... ]
$response = curl_exec($ch);
if ($response === false) {
$response = curl_error($ch);
}
curl_close($ch);
$arrayResponse = json_decode($response, true);
//Do something with your array
Introduction
I don't know what is the structure of the csv file you want to output. You should provide it in your question if you want a better quality answer. Keep in mind though, that you are using 2 different data structures :
JSON is a tree
CSV is a table
So having nested arrays in your json will make this work harder.
Step 1
Check if your json string is valid: json validator
As you will see, the json string response you provided is not.
For the rest of my answer i will consider this part of your response which i made valid :
$string = '
[{
"InvoiceNumberPrefix": "AB-",
"InvoiceNumber": 1000,
"OrderID": 1,
"CustomerID": 1,
"OrderDate": "2014-01-10T12:44:37",
"OrderStatusID": 1,
"LastUpdate": "0001-01-01T00:00:00",
"UserID": "",
"SalesPerson": "",
"ContinueURL": "http://71745179439.3dcart.net/continue_order.asp?orderkey=tl31S22wts7B0hF1",
"BillingFirstName": "John",
"BillingLastName": "Doe",
"BillingCompany": "",
"BillingAddress": "123 Street",
"BillingAddress2": "",
"BillingCity": "Coral Springs",
"BillingState": "FL",
"BillingZipCode": "33065",
"BillingCountry": "US",
"BillingPhoneNumber": "800-828-6650",
"BillingEmail": "test#3dcart.com",
"BillingPaymentMethod": "Online Credit Card",
"BillingOnLinePayment": true,
"BillingPaymentMethodID": "1",
"ShipmentList": [{
"ShipmentID": 0,
"ShipmentLastUpdate": "0001-01-01T00:00:00",
"ShipmentBoxes": 1,
"ShipmentInternalComment": "Sample Order from 3dcart",
"ShipmentOrderStatus": 1,
"ShipmentAddress": "123 Street",
"ShipmentAddress2": "",
"ShipmentAlias": "",
"ShipmentCity": "Coral Springs",
"ShipmentCompany": "",
"ShipmentCost": 0.0,
"ShipmentCountry": "US",
"ShipmentEmail": "",
"ShipmentFirstName": "Test",
"ShipmentLastName": "Test",
"ShipmentMethodID": 0,
"ShipmentMethodName": "Free Shipping",
"ShipmentShippedDate": "",
"ShipmentPhone": "800-828-6650",
"ShipmentState": "FL",
"ShipmentZipCode": "33065",
"ShipmentTax": 0.0,
"ShipmentWeight": 1.0,
"ShipmentTrackingCode": "",
"ShipmentUserID": "",
"ShipmentNumber": 1,
"ShipmentAddressTypeID": 0
}],
"OrderItemList": [{
"CatalogID": 3,
"ItemIndexID": 1,
"ItemID": "1003K",
"ItemShipmentID": 0,
"ItemQuantity": 1.0,
"ItemWarehouseID": 0
}]
}]';
Step 2
Use json_decode() to convert your json to an array this way : The 1st parameter is your json string and the 2nd is a boolean that when set to true will return an associative array. (manual: json_decode)
$array = json_decode($string, true);
Step 3
Create your csv file this way :
$f = fopen('output.csv', 'w');
foreach ($array as $row) {
$result = [];
array_walk_recursive($row, function($item) use (&$result) {
$result[] = $item;
});
fputcsv($f, $result);
}
Of course my answer is based on the json string provided in step 1 !
thanks, all I have to find a solution write curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); then the return value from curl_exec will be the actual result from the successful operation and set false display it only browser
I am trying to implement sketchfab api in my website. I got the code and access token from their website , I implemented everything but when I execute the code, I get a blank screen. What is the problem?
The first problem was with curl, I enabled it by going to php.ini file but then this blank screen problem.
<?php
$url = "https://api.sketchfab.com/v1/models";
$path = "./";
$filename = "m.3DS";
$description = "Test of the api with a simple model";
$token_api = "THE ACCESS TOKEN";
$title = "Uber Glasses";
$tags = "test collada glasses";
$private = 1;
$password = "Tr0b4dor&3";
$data = array(
"title" => $title,
"description" => $description,
"fileModel" => "#".$path.$filename,
"filenameModel" => $filename,
"tags" => $tags,
"token" => $token_api,
"private" => $private,
"password" => $password
);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $data
));
$response = curl_exec($ch);
curl_close($ch);
echo $response; // I am trying to echo the response here
?>
The call to the upload api will return a json that contains the id of the model. You can use this id to generate an url and make another call to the oEmbed api. pseudo code example:
// your curl setup
$response = curl_exec($ch);
// Response
{success: true, {result: {id: 'xxxxxx'} } when upload OK
{success: false, error: 'error message'} when upload error
$id = $response['result']['id'];
$call= "https://sketchfab.com/oembed?url=https://sketchfab.com/show/" . $id;
// do another curl call with $call content
// it will return a response like below but with your model information
// Response
{
provider_url: "http://sketchfab.com",
provider_name: "Sketchfab",
thumbnail_url: "https://sketchfab.com/urls/dGUrytaktlDeNudCEGKk31oTJY/thumbnail_448.png?v=24a1cb0590851ccfeeae01a2ca1eece1",
thumbnail_width: "448",
thumbnail_height: "280",
author_name: "Klaas Nienhuis",
author_url: "https://sketchfab.com/klaasnienhuis",
title: "Maison d'artiste",
html: "<iframe frameborder="0" width="640" height="320" webkitallowfullscreen="true" mozallowfullscreen="true" src="http://sketchfab.com/embed/dGUrytaktlDeNudCEGKk31oTJY?autostart=0&transparent=0&autospin=0&controls=1&watermark=0"></iframe>",
width: 640,
height: 320,
version: "1.0",
type: "rich"
}
If you have an issue with this try in the command line to print the result of call.