I am using this php library to communicate with the spotify api to get my user details. The spotify api returns user data which I then want to add to a json file. Basically, whatever is sent back from the api I want to append to the json file for each user.
The data returned from the api looks like the following when I do print_r($api->me()); This is basically coming from this api call.
stdClass Object ( [display_name] => Paul Flanagan
[email] => paulflanagan#gmail.com
[external_urls] => stdClass Object (
[spotify] => https://open.spotify.com/user/21aydctlhgjst3z7saj2rb4pq ) [followers] => stdClass Object (
[href] => [total] => 19 )
[href] => https://api.spotify.com/v1/users/2391231jasdasd1
[id] => 21aydctlhgjst3z7saj2rb4pq
[images] => Array ( [0] => stdClass Object (
[height] => [url] => https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/18301863_452622995075637_5517698155320169855_n.jpg?oh=9e949fafd3ee84705ea5c1fa1aa9c811&oe=59C9F63C
[width] => ) ) [type] => user [uri] => spotify:user:21aydctlhgjst3z7saj2rb4pq )
I want to write this code to a json file
I have attempted many approaches but as I am more javascript focused than php I am struggling to write the data correctly. My latest attempt at the code looks like this:
<?php
require 'vendor/autoload.php';
$session = new SpotifyWebAPI\Session(
'KEY1',
'KEY2',
'CALLBACK_URL'
);
$api = new SpotifyWebAPI\SpotifyWebAPI();
if (isset($_GET['code'])) {
$session->requestAccessToken($_GET['code']);
$api->setAccessToken($session->getAccessToken());
$file = "users.json";
$json = json_decode(file_get_contents($file), true);
$file = fopen($file,'w+');
fwrite($file, $api->me());
fclose($file);
print_r($api->me());
} else {
$options = [
'scope' => [
'user-read-email',
],
];
header('Location: ' . $session->getAuthorizeUrl($options)$
die();
}
?>
As $api->me() returns object - you cannot write it to a file directly. You should convert object to a string. Simple way is to json_encode it:
$file = "users.json";
$json = json_decode(file_get_contents($file), true);
$file = fopen($file,'w+');
fwrite($file, json_encode($api->me()));
fclose($file);
Next problem - is overwriting data. As you open file with w+ - you file gets truncated to 0 length.
Solution here depends on what you need with previous data. If you want to rewrite some data - I think current behaviour does it already.
If you want to append data to a file - you should use another mode when you open file, for example a+. But in this case, file contents won't be correct json, as you write to file not a single json string, but several strings, which is not correct json. So, it's up to you to find a proper solution.
Update:
According to file name, I suppose you store users in it. So, I think there's a list of users, encoded in json. So, a brief solution can be:
$file = "users.json";
$json = json_decode(file_get_contents($file), true);
// Now $json stores list of you current users. I suppose it's a simple array of arrays
// This is data for a new user
$new_user = $api->me();
// as data `$new_user` is object, I think you need to convert it to array
// this can be done as:
$new_user = json_decode(json_encode($new_user), true);
// now, add new user to existsing array
$json[] = $new_user;
$file = fopen($file,'w+');
// now we can encode `$json` back and write it to a file
fwrite($file, json_encode($json));
fclose($file);
Related
I am consuming a web service that returns some XML data. The problems start when I convert the xml data to json. Some elements that are supposed to return an array of objects, when they have only one value, they are not converted to an array with a single object inside, they turn into an object. So instead of having:
{
"products":[ { "title":"Title 1", "attributes":[{"color":"blue"}] } ]
}
I get
{
"products":{ "title":"Title 1", "attributes":{"color":"blue"} }
}
and the php array looks like this
[products] => Array ( [title] => Title 1 [attributes] => Array ( [color] => blue ) )
instead of this
[products] => Array ( [0] => Array ( [title] => Title 1
[attributes] => Array ([0] => Array ([color] => blue ) ) )
So what I have done is the below:
$xml = simplexml_load_string($messageData);
$json = json_encode($xml);
$array = json_decode($json, TRUE);
if (isset($array['products']) && !isset($array['products'][0])) {
$array['products'] = array($array['products']);
}
I check if there is an array named products and if it doesn't have an index 0, I nest it inside a new array.
This does the job. Then I do the same for the attributes array like this:
$products = $array['products'];
$array['products'] = [];
foreach ($products as $product) {
if (isset($product['attributes']) && !isset($product['attributes'][0])) {
$product['attributes'] = array($product['attributes']);
}
array_push($array['products'], product);
}
Here, I bind the products array to a variable called products to use it in the loop, then I empty the array and after I create the new attributes array, I populate the products array with the changed products.
My question is:
Is there a better way to deal with this thing? I don't like what I am doing here, but I can't think of anything else...
EDIT
This is my soap request:
$client = new SoapClient($wsdl, $soapOptions);
$soapHeader = WsSecurity::createWsSecuritySoapHeader($username, $password, false, $synced, 60, true, true, false, true);
$client->__setSoapHeaders($soapHeader);
$response = $client->dateRetrieveMovement($dateMovementRequest);
$movements = $response->DateMovementRequestResult->movements;
$movementInfo = $movements->movementInfo;
$messages = $movementInfo->messages->messageExchanged;
$messageData = $messages->IEMessage->xmlData;
$xml = simplexml_load_string($messageData);
$json = json_encode($xml);
$array = json_decode($json, TRUE);
The question is "is there a better way of doing the XML to JSON conversion", and I think the answer is "not without doing some coding".
Standard XML-to-JSON conversion libraries simply don't know enough about the semantics of your data model to produce a decent representation of your data. In theory a tool could try an extract such information from a schema, or elsewhere, but I don't know of any that does.
Writing a custom XSLT transformation to produce exactly the JSON you want is not too difficult, especially with XSLT 3.0, and this may well be less effort than patching up the JSON in the receiving application in the way you describe.
i hava file called test.php,in this file I have array like this :
array(
[0] => $x_axis_t1 = "1,2,3,4,5";
[1] => $y_axis_t1 = "1,2,4,3,2";
[2] => $x_axis_t2 = "1,22,73,49,5";
[3] => $y_axis_t2 = "1,9,8,2,1";
)
This array I need to call or read in another file called test2.php, is there any way to read the array, if it is possible could please explain.
Note:in test.php file array has no name.
Thanks
If I understand you clearly you just have to include test.php in test2.php
//In test2.php you have:
<?php
include 'test.php';
The above will make array accessible in test2.php
Meanwhile, I doubt that array is valid I believe you are better off storing it as variables or better still give the array a name with indexes reflecting the variable names above.
What are you trying to do precisely?
You can use serialize or json_encode PHP functions to serialize the array data and then store in a file as plain text, like below:
$data = array(
[0] => "1,2,3,4,5",
[0] => "1,2,4,3,2",
[0] => "1,22,73,49,5",
[0] => "1,9,8,2,1",
);
$data = serialize( $data );
file_put_contents( 'test.php' , $data );
The above will store the array in test.php file in serialized form. The next is to read this data to some variable of your choice.
$new_data = file_get_contents( 'test.php' );
$new_array = unserialize( $new_data );
$new_array now has the array data loaded from the external file. Hope this solves the problem.
I have an empty array in a remote file but intend to momentarily add and alter objects in it. However, after adding an initial first set of objects, the array does not accept any more values. My error log reports unexpected 'Object' (T_STRING), expecting ')' meaning it regards the keyword "Object" as a string imputed by me so I guess the problem originates from my array structure. Here is the code I used in adding the objects
include 'all_users.php';
$francis_udeh = new Admin("francis_udeh");
$all_users['francis_udeh'] = $francis_udeh;
$victor_nwafor = new Member("victor_nwafor");
$all_users['victor_nwafor'] = $victor_nwafor;
$print_arr = print_r($all_users, TRUE);
$updated_arr = "<?php \n \$all_users = $print_arr; \n?>";
file_put_contents('all_users.php', $updated_arr);
returns the following in the remote file
<?php
$all_users = Array
(
[francis_udeh] => Admin Object
(
[name] => francis udeh
[pagename] => francis.udeh
[can_comment] => 1
[can_view_announcements] => 1
[profile_pic] => /blog/accounts/assets/user.png
[can_delete_comment] => 1
)
[victor_nwafor] => Member Object
(
[name] => victor nwafor
[pagename] => victor.nwafor
[can_comment] => 1
[can_view_announcements] => 1
[profile_pic] => /blog/accounts/assets/user.png
)
);
?>
(which, by the way, is what I want). However, when I try
include 'all_users.php';
$raheem_sadiq = new Member("raheem_sadiq");
$all_users['raheem_sadiq'] = $raheem_sadiq;
$print_arr = print_r($all_users, TRUE);
$updated_arr = "<?php \n \$all_users = $print_arr; \n?>";
file_put_contents('all_users.php', $updated_arr);
it returns the error I posted earlier resulting in the array not changing. What am I doing wrong?
You include all_users.php at the beginning of code, but after first file_put_contents() it's a not correct php code in this file.
As #Indra already mentioned: the output given by print_r() is human readable, but not valid php code. If you don't have the possibilty to pass the data via a data storage (like mysql), it might be a workaround to put it to the file with serialize(). Alternatively, you could also use json (as your objects seem to be data access objects of some same kind) and then instantiate the objects remotely.
Hope this helps,
Greetings
I'm getting response from webservice.This is for response:
$endpoint = 'http://.....';
$mynamespace = 'http://........';
$client = new nusoap_client($endpoint, true);
$response = $client->call('SaleWithTicket', $param, $mynamespace);
And if I print it I'm getting this result
Array
(
[SaleWithTicketResult] => Array
(
[TicketObjectId] => e1f511a8-610c-4db9-8c22-1effaf4c9ad9
[TransactionDate] => 2015-06-18T07:00:18.9651562+03:00
[StatusCode] => 0
[RedirectUrl] => https://.........
)
)
These are dynamic structered.
I want auto redirection however I couldn't find a way to go.
$location=$response['SaleWithTicketResult']['RedirectUrl'];
header("Location: $location");
What's hard there? And if that $result doesn't follow a defined structure and can be in a totally different format on a different day then whatever solution you come up with will be just a hack.
I have a piece of JSON that I'm parsing with php. I need to get one of the pieces of data out of it.
Here's the output of the json when I do a print_r:
Array ( [deviceId] => 07a9727e-3fe5-4f44-9765-134388241f39 [programId] => 3895 [serviceId] => 19977 [createdAt] => 2013-12-12T07:19:04.466Z [updatedAt] => 2013-12-12T07:19:04.466Z [objectId] => 7TxmL2GiXq )
Here's my code trying to extract deviceId:
$objectData = json_decode($data, true);
print_r($objectData);
$deviceId = $objectData->deviceId;
$deviceId is coming back empty.
Any help would be appreciated. Thanks.
Do this:
$deviceId = $objectData['deviceId'];
You are using the optional second parameter TRUE in your json_decode call, which converts it into an associative array instead of an object.
Alternatively:
$objectData = json_decode($data);
$deviceId = $objectData->deviceId; // Works