Sending JSON Array via PHP (Campaign Monitor) - php

I have a sample JSON Array labeled sample.txt that is sent from a sweepstakes form that captures a user's name and e-mail. I'm using WooBox so the JSON Array sends information over by each entry, so there are two entries here: http://pastebin.ca/3409546
On a previous question, I was told to break the ][ so that JSON_ENCODE can figure the separate entries. I would like to capture just the name and e-mail and import the array to my e-mail database (campaign monitor).
My question is: How do I add JSON variable labels to an array? If you see my code, I have tried to use the label $email. Is this the correct form or should it be email[0] with a for loop?
$url = 'http://www.mywebsite.com/sweeps/test.txt';
$content = file_get_contents($url);
$json = json_decode($content,true);
$tmp = explode('][', $json_string);
if (!count($tmp)) {
$json = json_decode($json_string);
var_dump($json);
} else {
foreach ($tmp as $json_part) {
$json = json_decode('['.rtrim(ltrim($json_string, '['), ']').']');
var_dump($json);
}
}
require_once 'csrest_general.php';
require_once 'csrest_subscribers.php';
$auth = array(
'api_key' => 'xxxxxxxxxxxxxxx');
$wrap = new CS_REST_Subscribers('xxxxxxxxxx', $auth);
$result = $wrap->add($json(
'EmailAddress' => $email,
'Name' => $custom_3_first,
'Resubscribe' => false
));
https://github.com/campaignmonitor/createsend-php/blob/master/samples/subscriber/add.php

This should have been fairly easy: if you have a JSON string and you call json_decode($string, true) on it, you get its equivalent in a PHP variable, plain and simple. From there, you can access it like you would any PHP array, object, etc.
The problem is, you don't have a proper JSON string. You have a string that looks like JSON, but isn't valid JSON. Run it through a linter and you'll see what I mean.
PHP doesn't know what to do with your supposed JSON, so you have to resort to manual parsing, which is not a path I would recommend. Still, you were almost there.
require_once 'csrest_general.php';
require_once 'csrest_subscribers.php';
$auth = array('api_key' => 'xxxxxxxxxxxxxxx');
$wrap = new CS_REST_Subscribers('xxxxxxxxxx', $auth);
$url = 'http://www.mywebsite.com/sweeps/test.txt';
$content = file_get_contents($url);
$tmp = explode('][', $content);
foreach ($tmp as $json_part) {
$user = json_decode('['.rtrim(ltrim($json_string, '['), ']').']', true);
$result = $wrap->add(array(
'EmailAddress' => $user->email,
'Name' => $user->fullname,
'Resubscribe' => true
));
}

Related

Get an array in a php file from http request

I'm learning php and I'm trying to get a php file from a http request using Guzzle and then just take a particular array from those contents and ignore the rest. But I'm unsure how to get that array.
<?php
require_once "vendor/autoload.php";
use GuzzleHttp\Client;
$client = new Client();
$response = $client->request('GET', 'http://api-address/file.php');
$body = $response->getBody();
$decoded = json_decode($body, true);
$contents = file_get_contents($decoded);
When I print $contents it looks as expected, for example:
<?php
$var = "example string";
$array = [
[
'name' => 'stuff I need'
]
];
I want to just get the array, iterate through it and write each to a file but I don't know how to get just that and ignore the other stuff that isn't in that array it if that makes sense. Any help would be appreciated.
You are using ...
json_decode($body, true);
That method converts the content to array, that means that probably if you do a ...
var_dump($decoded);
you can see an array that it contents arrays inside ...
Well, I mean, you can get ...
$array = [
[
'name' => 'stuff I need'
]
];
Navigating into $json_decode() array.
If you are asking the how, well, just use the next step ...
$contentArray = $decoded[1] //With this you can get the array that you need.

.JSON file creates NULL value via PHP

So I'm trying to figure out why I get a NULL value in my .json file after I try to write the array to it. It only happens with the 'array_push' line after creating a new file. If there is a .json file already there with a value in it, it'll write to it correctly. The only thing I could guess was the file is missing the '{' and '}' in it upon creation.
I've got a small work around so far, but not sure that this is the right way to do it. Can someone tell me if this is good or bad?
Just to clarify, the .json document only holds the vault of NULL, there are no array elements or anything in the file besides the word NULL.
//CHECK IF FILE EXISTS, ELSE CREATE IT
$log_filename = "./site_files/logs/error-404-log.json";
if(!file_exists($log_filename)) {
touch($log_filename);
//LINE BELOW IS MY WORK AROUND, I'M NOT SURE IF THIS IS THE RIGHT WAY
file_put_contents($log_filename, json_encode(json_decode("{}")));
echo "$log_filename was created. <br />";
}
$log_array = array();
$new_data = array(
'current_date_stamp' => $current_date_stamp,
'current_page_trail' => $current_page_trail
);
$json_data = file_get_contents($log_filename);
if($log_array != "") { $log_array = json_decode($json_data, true); }
//WHEN CREATING A NEW FILE, ARRAY_PUSH GIVES ERROR
array_push($log_array, $new_data);
$json_data = json_encode($log_array, JSON_PRETTY_PRINT);
file_put_contents($log_filename, $json_data);
$log_filename = "error-404-log.json"; // establish the path/to/filename.json
if (file_exists($log_filename)) { // if path/to/filename.json exists
$json = file_get_contents($log_filename); // access PRETTY json string
echo "pre-existing data: <div><pre>$json</pre></div><br>"; // display json string
$array = json_decode($json, true); // decode to prepare for new data
}
// data always maintains the same structure: an array of 2-element arrays
$array[] = [
'current_date_stamp' => date('Y-m-d H:i:s'),
'current_page_trail' => "foo"
];
// create/update the file
$new_json = json_encode($array, JSON_PRETTY_PRINT); // re-encode updated array data
echo "new data: <div><pre>$new_json</pre></div>"; // display new json string
file_put_contents($log_filename, $new_json); // create or overwrite file
Your code is failing because you are comparing $log_array with an empty string, this condition will always pass because this array will never be an empty string. In the if statement you decode the contents of the file, when the file has no content this will be an empty string and it will return NULL, after this you write this NULL value to your file. If you check if $json_data is an empty string your code should work, I would also recommend doing it like this:
$log_array = array();
$new_data = array(
'current_date_stamp' => $current_date_stamp,
'current_page_trail' => $current_page_trail
);
$json_data = file_get_contents($log_filename);
if($json_data != "") {
$log_array = json_decode($json_data, true);
//WHEN CREATING A NEW FILE, ARRAY_PUSH GIVES ERROR
array_push($log_array, $new_data);
$json_data = json_encode($log_array, JSON_PRETTY_PRINT);
file_put_contents($log_filename, $json_data);
}
This is better since if the string is empty all other actions are irrelevant.

PHP Decoding JSON - Null Output

I have probably spent all day trying to figure this out. I have read multiple questions here on stack and also have been reading articles and checking on documentation, but I can't seem to figure out why this batch of code just produces a null output. Am I missing brackets, calling something wrong, ect?
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str);
$temp = $json['main']['temp_min'];
$content = $temp;
$array = array(
"content" => $content,
refresh_requency => 30
);
echo json_encode($array);
?>
Again what I'm asking is can someone point out to me or tell me what I'm doing wrong. Is it my server that's just not handling the data correctly? That could be a possibility.
One other thing I've tried is to just print out $temp and/or the other variable like $str. When I do that though they don't even show up so that's what I think my problem is just not sure how to fix it.
Update
I've come to the conclusion that it's my web hosting service. As if I add var_dump($json) I get a null output null output.
Also to confirm that its my webhost if I run error_reporting(E_ALL); ini_set('display_errors', 1); it points to the file php.ini not allowing outgoing connections. I edited that same file on my local home server(raspberry pi) ran the same file and it works fine.
Below is the working solution for your above code:
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str, true);
$temp = $json['main']['temp_min'];
$content = $temp;
$array = array(
"content" => $content,
"refresh_requency" => 30
);
echo json_encode($array);
?>
When I executed your code, I found 2 problem into your code snippet:
1) You were trying to use object of type stdClass as array.
Solution:
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str);
$temp = $json->main->temp_min;
$content = $temp;
$array = array(
"content" => $content,
"refresh_requency" => 30
);
echo json_encode($array);
?>
2) You did not put array key into quotes:
$array = array(
"content" => $content,
refresh_requency => 30
);
It should be :
$array = array(
"content" => $content,
"refresh_requency" => 30
);
Access $temp like this
$temp = $json->main->temp_min;
you will get the desired output.
Also, you need to allow allow_url_fopen in your php.ini config file. Some hosts disallow it for security reasons
$json = json_decode($str, true);
You need second argument to convert json string into associative array instead of the object. And you are trying to use array ($json['main']['temp_min']), not object. Also
$array = array(
"content" => $content,
"refresh_requency" => 30
);
The code looks like
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str, true);
$content = $json['main']['temp_min'];
$array = array(
"content" => $content,
"refresh_requency" => 30
);
echo json_encode($array);
And result is http://codepad.viper-7.com/euBNAk :
{"content":44.6,"refresh_requency":30}
The second parameter of json_decode() is assoc (associative). By default it is 0. When it is 0 (default) the json_decode() will return an object, not an array. That's why you are unable to access temp_min by using $json['main']['temp_min'];
However If you use with the value 1 as second parameter, the function will return an array. Parameter 1 means setting associative to 1 (true). So use $json = json_decode($str, true); instead of $json = json_decode($str);. You will be able to access with $json['main']['temp_min']; now.
Also you forgot double quote on line 13 (refresh_requency). Goodluck.
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str, true);
$temp = $json['main']['temp_min'];
$content = $temp;
$array = array(
"content" => $content,
"refresh_requency" => 30
);
echo json_encode($array);
Just want help
I change your code like this and that be correctly
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str, TRUE); // Wrong here
$temp = $json['main']['temp_min'];
$content = $temp;
$array = array(
"content" => $content,
"refresh_requency" => 30 // And wrong here, it's must string
);
echo json_encode($array);
?>
More information about json decode in php to array or object http://php.net/manual/en/function.json-decode.php

array_key_exists() expects parameter 2 to be array, string when using pushWoosh Class

I am having some trouble implementing the pushwoosh class http://astutech.github.io/PushWooshPHPLibrary/index.html. I have everything set up but i am getting an error with the array from the class.
This is the code i provied to the class:
<?php
require '../core/init.php';
//get values from the clientside
$sendID = $_POST['sendID'];
$memID = $_POST['memID'];
//get sender name
$qry = $users->userdata($memID);
$sendName = $qry['name'];
//get receiving token
$qry2 = $users->getTokenForPush($sendID);
$deviceToken = $qry2['token'];
//i have testet that $deviceToken actually returns the $deviceToken so thats not the problem
//this is the array that the php class requires.
$pushArray = array(
'content' => 'New message from ' . $sendName,
'devices' => $deviceToken,
);
$push->createMessage($pushArray, 'now', null);
?>
And this is the actually code for the createMessage() method
public function createMessage(array $pushes, $sendDate = 'now', $link = null,
$ios_badges = 1)
{
// Get the config settings
$config = $this->config;
// Store the message data
$data = array(
'application' => $config['application'],
'username' => $config['username'],
'password' => $config['password']
);
// Loop through each push and add them to the notifications array
foreach ($pushes as $push) {
$pushData = array(
'send_date' => $sendDate,
'content' => $push['content'],
'ios_badges' => $ios_badges
);
// If a list of devices is specified, add that to the push data
if (array_key_exists('devices', $push)) {
$pushData['devices'] = $push['devices'];
}
// If a link is specified, add that to the push data
if ($link) {
$pushData['link'] = $link;
}
$data['notifications'][] = $pushData;
}
// Send the message
$response = $this->pwCall('createMessage', $data);
// Return a value
return $response;
}
}
Is there a bright mind out there that can tell me whats wrong?
If I understand, your are trying to if your are currently reading the devices sub-array. You should try this:
foreach ($pushes as $key => $push) {
...
// If a list of devices is specified, add that to the push data
if ($key == 'devices') {
$pushData['devices'] = $push['devices'];
}
You iterate over $pushes, which is array('content' => ..., 'devices' => ...). You will first have $key = content, the $key = 'devices'.
It looks like the createMessage function expects an array of messages, but you are passing in one message directly. Try this instead:
$push->createMessage(array($pushArray), 'now', null);
The class is expecting an array of arrays; you are just providing an array.
You could do something like this
//this is the array that the php class requires.
$pushArrayData = array(
'content' => 'New message from ' . $sendName,
'devices' => $deviceToken,
);
$pushArray[] = $pushArrayData
Will you ever want to handle multiple messages? It makes a difference in how I would do it.

Amazon MWS Product Feed Not Submitting

I am working on the Amazon API. I want to submit the product feed on amazon account.
I have validated the XML file (product feed) by the Amazon Scratch Pad and i get the Response that Feed is submitted but when i run the script, to submit the same feed by script, i don't get any response.
Here is my code :
$req = new MarketplaceWebService_Model_SubmitFeedRequest();
$req->setMerchant(MERCHANTID);
$req->setMarketplaceIdList(MARKETPLACEID);
$req->setFeedType('_POST_PRODUCT_DATA_');
$req->setContentMd5(base64_encode(md5(stream_get_contents($fh), true)));
rewind($fh);
$req->setPurgeAndReplace(true);
$req->setFeedContent($fh);
$res = $mws->submitFeed($request);
echo $res;
I am unable to get the response, when i echo the $res.
I have changed the $res = $mws->submitFeed($request); to $res = $mws->submitFeed($req);. Still no success in submitting the feed. I am not getting any response header that Amazon return while submitting the feed.
The code is like this :
$req = new MarketplaceWebService_Model_SubmitFeedRequest();
$fh = fopen('feed.xml', 'r');
$req->setMerchant(MERCHANTID);
$req->setMarketplaceIdList(MARKETPLACEID);
$req->setFeedType('_POST_PRODUCT_DATA_');
$req->setContentMd5(base64_encode(md5(stream_get_contents($fh), true)));
rewind($fh);
$req->setPurgeAndReplace(true);
$req->setFeedContent($fh);
$res = $mws->submitFeed($req);
echo $res;
Apart from other things that might go wrong: You are submitting $request, while the thing you probably want to submit is $req.
Edit: Since you corrected this mistake but still have no result...:
submitFeed() returns a MarketplaceWebService_Model_SubmitFeedResponse object.
Echo does not work with objects, unless the object has a __toString() method, which this class doesn't. Try using print_r($res) or var_dump($res) instead.
Try this
$marketplaceIdArray = array("Id" => array($MARKETPLACE_ID));
$feedHandle = #fopen('php://temp', 'rw+');
fwrite($feedHandle, $feed);
rewind($feedHandle);
$parameters = array(
'Merchant' => $MERCHANT_ID,
'MarketplaceIdList' => $marketplaceIdArray,
'FeedType' => '_POST_PRODUCT_DATA_',
'FeedContent' => $feedHandle,
'PurgeAndReplace' => false,
'ContentMd5' => base64_encode(md5(stream_get_contents($feedHandle), true))
);
rewind($feedHandle);
$request = new MarketplaceWebService_Model_SubmitFeedRequest($parameters);
$return_feed = invokeSubmitFeed($service, $request);
fclose($feedHandle);

Categories