Invalid Array from json_decode() - php

I have a PHP file that grabs a .txt file and decodes the JSON to push the user's e-mail and name entry to my campaign monitor database. The JSON is wonky because new entries are added with a ][ as seen in this example:
[{"email":"drake.scott#test.com","createdate":"2016-03-23 10:44:52","from_email":null,"from_liked_pageid":null,"source":"direct","bonus_entry_url":"\/xxxbyn\/h1lvw5","entry_url":"https:\/\/admin.woobox.com\/manage\/offers\/entries\/20160314-1\/tu%2BcJmnsgyUxE7HM9BCqnRjnza27dGIdr%2BHymHrFmFoprsRgkhZradPrTJ5s18p6ewxYeOOKLpObd%2FWGAS%2BDRw%3D%3D","shareurl":"http:\/\/woobox.com\/qbxbyn\/h1lvw5","picked":"0","actionbutton":"","custom_3_first":"drake","custom_3_last":"scott","custom_4":"4146583264","fullname":"drake scott","id":"vvvbyn"}]
[{"email":"john.roberts#test.com","createdate":"2016-03-23 10:44:52","from_email":null,"from_liked_pageid":null,"source":"direct","bonus_entry_url":"\/xxx\/h1lvw5","entry_url":"https:\/\/admin.woobox.com\/manage\/offers\/entries\/20160314-1\/tu%2BcJmnsgyUxE7HM9BCqnRjnza27dGIdr%2BHymHrFmFoprsRgkhZradPrTJ5s18p6ewxYeOOKLpObd%2FWGAS%2BDRw%3D%3D","shareurl":"http:\/\/woobox.com\/vvvbyn\/h1lvw5","picked":"0","actionbutton":"","custom_3_first":"john","custom_3_last":"adams","custom_4":"4146585018","fullname":"john adams","id":"vvvbyn"}]
The problem I am having right now is uploading the entries to my database. I have managed to strip the ][ and doing a var_dump($content); shows a valid JSON string. However, doing var_dump($user) gives me 0 array(0) { }.
The entries will not upload to my database because there is essentially nothing in my array. Can anyone give me some insight on how to proceed?
<?php
require_once 'csrest_general.php';
require_once 'csrest_subscribers.php';
$auth = array(
'api_key' => 'xxxxxxxxxx');
$wrap = new CS_REST_Subscribers('xxxxxxxxxx', $auth);
$url = 'http://www.mywebsite.com/sweeps/test.txt';
$content = file_get_contents($url);
$content = str_replace('}][{', '},{', $content);
$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
));
}
if($result->was_successful()) {
echo "Subscribed with code ".$result->http_status_code;
}
else {
echo "failed";
var_dump($result->response);
var_dump($user);
}
?>

There are multiple JSON objects concatenated in the file. The easiest way to make the JSON valid is to create an array:
$content = str_replace('][', ',', $content);
$users = json_decode($content, true);
Then you have a multi-dimensional array with multiple users that you will need to decide what you want from it:
print_r($users);
foreach($users as $user) {
echo $user['email'] . "\n";
}

Related

Want to get just two object in json

I am trying to make a code verifier with the following code. I've looked at the answers in StackOverflow but couldn't get the right result.
The code is working fine but I want to echo just two value.
validate.php page code is here:
if(isset($apKey) && isset($code)) {
$en = new En();
$Key = $apKey;
$Codes = $code;
if($Key == null || $Codes == null) {
echo json_encode(['data' => 'No Key or code found, Please try again']);
exit;
}
$response = $en->validate($Key,$Codes);
$result = json_decode($response);
$elements = json_encode(['data' => $result]);
echo $elements;
exit;
}
echo json_encode(['data' => 'No Key or code found, Please try again']);
exit;
Now I am trying to check this validate page results using this code:
$siteurl = urlencode($_SERVER['SERVER_NAME']);
$arrContextOptions = array(
"ssl" => array(
"verify_peer" => false,
"verify_peer_name" => false
)
);
$file = file_get_contents('http://www.validates.com/validate.php?code=' . $check , false, stream_context_create($arrContextOptions));
$checks = json_decode($file, true);
$elements = $checks['data'];
echo print_r($elements);
So the results something like this:
Array
(
[buyer] => abcd
)
So what I want to do. I want to echo just buyer and error message after this code: $checks = json_decode($file, true);
The error result is here:
{"data":{"error":404,"description":"No sale belonging to the current user found with that code"}}
Like for example:
if(buyer){echo 'true';}
if(error message){echo 'error';}
I guess you can check with array_key_exists if there is error. You can do something like this:
$checks = json_decode($file, true);
$data = $checks['data'];
if (array_key_exists("error", $data))
echo $data["description"];
else
echo $data["buyer"];

Convert String back into an array PHP

I have two different torrent scrapping classes and I want to combine them, they are working fine separately but the only problem is, when I convert my string into an array, it does not work.
That's the codes I am using so far.
<?php
require 'scraper.php';
require 'tor-info.php';
$scraper = new Scrapeer\Scraper();
$torrent = new Torrent( './test.torrent' );
$hashix = $torrent->hash_info();
var_dump($torrent->scrape()); // shows trackers list like this array(21) { ["udp://tracker4.piratux.com:6969/announce"]=> bool(false) ["udp://tracker.trackerfix.com:80/announce"]=> bool(false) ["udp://tracker.pomf.se:80/announce"]=> bool(false) ["udp://torrent.gresille.org:80/announce"]=> bool(false) so on..
$trackers = array( "udp://tracker4.piratux.com:6969/announce", "udp://tracker.trackerfix.com:80/announce", "udp://tracker.pomf.se:80/announce" ); // now here we need that trackers list
$hash = array( $hashix );
$info = $scraper->scrape( $hash, $trackers );
//print_r( $info );
echo '<br><hr>';
foreach ($info as $key => $value) {
echo 'SEEDS :' .$value['seeders'].'<br />';
echo 'LEECHES :' .$value['leechers'].'<br />';
}
?>
In the first part I converted the array into String to get the readable result, and then in the second part I needed to convert that string back into single array to produce the result.
Why don't you just make them an array to begin with?
<?php
require 'scraper.php';
require 'tor-info.php';
$scraper = new Scrapeer\Scraper();
$torrent = new Torrent( './test.torrent' );
$hashix = $torrent->hash_info();
$trackers = array_keys($torrent->scrape());
$hash = array( $hashix );
$info = $scraper->scrape( $hash, $trackers );
echo '<br><hr>';
foreach ($info as $key => $value) {
echo 'SEEDS :' .$value['seeders'].'<br />';
echo 'LEECHES :' .$value['leechers'].'<br />';
}
Since your string looks like this (from comment) : "udp://tracker4.piratux.com:6969/announce","udp://tracker.trackerfix.com:80/announce" you could use PHP's explode() function like so:
$recombined = explode(',', str_replace('"', '', $trackers));

php file that returns a string json encode didnt work

I have an php file that gives me the response i need as a string, i need it to be an array encoded in json, im not that good with php, can any one help ?
this is how it works fine as a string
- printf("user: \"%s\" \"%s\" email: \"%s\" \n", $row['firstname'], $row['lastname'],$row['email']);
But i need it as an array in json that is how i tried to do it
-array_push($mynewArray,array("firstname \%s"=>$row['firstname'],"lastname \%s"=>$row['lastname'],"email \%s"=>$row['email']));
echo json_encode($mynewArray);
this is the screen shot that shows how i tried to do it
I think you could try like this assuming the recordset is generated correctly and available in the var $row
$mynewArray=array();
foreach($result as $row){
$mynewArray[]=$row;
}
echo json_encode($mynewArray);
Or
$mynewArray=array();
foreach( $result as $row ){
$mynewArray[]=array(
'firstname'=>$row['firstname'],
'lastname'=>$row['lastname'],
'email'=>$row['email'],
);
}
echo json_encode($mynewArray);
This might be what you're after:
<?php
$cluster = Cassandra::cluster()
->build();
$keyspace = 'msata';
$session = $cluster->connect($keyspace);
$result = $session->execute(new Cassandra\SimpleStatement
("SELECT * FROM msata.users")
);
// Create the variable array here so it's used correctly in the loop
$mynewArray = array();
foreach( $result as $row ){
// Create an array for each individual user
$user_array = array( 'firstname' => $row['firstname'], 'lastname' => $row['lastname'], 'email' => $row['lastname'] );
// Add the array to the main array
$mynewArray = array_push( $mynewArray, $user_array );
}
echo json_encode( $mynewArray );

JSON encode an array with file_get_contents

I'm trying to figure out how to encode the following:
$data[] = '';
//check if real player
if($steam_name != null){
$data['valid'] = true;
$data['url'] = "http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key=key&vanityurl=$steam_name";
echo json_encode($data, file_get_contents($data->url));
}else{
$data['valid'] = false;
echo json_encode($data);
}
I understand how to get the data, but it seems to not be sending through.
Thanks!
My attempt as per answer below. This does not work:
$data[] = '';
//check if real player
if($steam_name != null){
$data['valid'] = true;
$url = 'http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?';
$params = [
'key' => 'key',
'vanityurl' => $steam_name,
];
$data['url'] = $url . http_build_query($params);
echo json_encode($data);
}else{
$data['valid'] = false;
echo json_encode($data);
}
You should be using http_build_query() to accomplish that.
$url = 'http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?';
$params = [
'key' => 'abc123',
'vanityurl' => $steam_name,
];
$data['url'] = $url . http_build_query($params);
That will handle the proper encoding for the parameters.
Additionally, $data is an array here, you can't call it like an object in your file_get_contents call. I'm surprised you aren't getting an exception. Also, json_encode doesn't accept parameters like that. Try this:
// Store the API response in your data array
$data['response'] = file_get_contents($data['url']);
// Return it so you can use it
return json_encode($data);
If the response is JSON, you can decode it:
$data['response'] = json_decode(file_get_contents($data['url']));

PHP-cURL Adding entry to an array in a function not working

I can echo the response i get just fine in the function request_callback so I thought it trivial to just save the response into an array associative_array[], however this yields just single entries, like the array gets wiped after every entry.
I make use of https://github.com/LionsAd/rolling-curl/blob/master/RollingCurl.php
<?php
# Get the all the items numbers
$url1 = "http://api.guildwars2.com/v2/commerce/listings";
$response1 = file_get_contents($url1);
$data1 = json_decode($response1, true);
#retrieve item names and link with numbers
function request_callback($response) {
$temporary_array = json_decode($response, true);
$associative_array[] = array('name' => $temporary_array['name'],'id' => $temporary_array['id']);
// array[] places the new entry at end of urls stack, faster then array_push($array, new entry);
print_r ($associative_array);
echo "\n";
}
# Multiple curl request
require("rollingcurl.php");
for ($x=0;$x<5;$x++){
$itemurl1 = "http://api.guildwars2.com/v2/items/{$data1[$x]}";
$urls[$x]= $itemurl1;
}
$rc = new RollingCurl("request_callback");
$rc->window_size = 20;
foreach ($urls as $url) {
$request = new RollingCurlRequest ( $url ) ;
$rc -> add ( $request ) ;
}
$rc->execute();
?>
Your array is local to your function, hence reseting on each call.
Try adding global declaration and you will get what you expect (all values);
function request_callback($response) {
global $associative_array;
$temporary_array = json_decode($response, true);
$associative_array[] = array('name' => $temporary_array['name'],'id' => $temporary_array['id']);
// array[] places the new entry at end of urls stack, faster then array_push($array, new entry);
print_r ($associative_array);
echo "\n";
}
I'd create your array outside of your function. It looks like you're creating a new array on every function call.
$associative_array = array();
function request_callback($response) {
global $associative_array;
$temporary_array = json_decode($response, true);
$associative_array[] = array('name' => $temporary_array['name'],'id' => $temporary_array['id']);
// array[] places the new entry at end of urls stack, faster then array_push($array, new entry);
print_r ($associative_array);
echo "\n";
}

Categories