Convert php output to JSON - php

I have the following output from a PHP script:
one#gmail.com test1
two#gmail.com test2
which is generated from the following:
$i = 0;
$header = array();
while (!feof($handle)) {
$buffer = fgets($handle, $chunk_size);
if (trim($buffer)!=''){
$obj = json_decode($buffer);
echo $obj[0]." ".$obj[2]."<br>";
$i++;
}
}
fclose($handle);
How can i convert the output of the script into a JSON format of :
{"emails":[{"email":"one#gmail.com","option":test1"},{"email":"two#gmail.com","option":test2"}]}
The script was taken from the Mailchimp API which list the subscribers of a list.
Here is the script for reference:
<?php
$apikey = '1234-us7';
$list_id = '1234';
$chunk_size = 4096; //in bytes
$url = 'http://us7.api.mailchimp.com/export/1.0/list?apikey='.$apikey.'&id='.$list_id.'&output=json';
/** a more robust client can be built using fsockopen **/
$handle = #fopen($url,'r');
if (!$handle) {
echo "failed to access url\n";
} else {
$i = 0;
$header = array();
while (!feof($handle)) {
$buffer = fgets($handle, $chunk_size);
if (trim($buffer)!=''){
$obj = json_decode($buffer);
if ($i==0){
//store the header row
$header = $obj;
} else {
//echo, write to a file, queue a job, etc.
echo $obj[0]." ".$obj[2]."<br>";
}
$i++;
}
}
fclose($handle);
}
?>
Thank you!

It appears to already be in JSON, because you are using json_decode to get that output. So just... stop using json_decode on it.

As #jessica has already mentioned, it appears that $buffer is coming to you as JSON, because you are running json_decode(&buffer) on it.
However, if you want to do some manipulations, arrange the data so you build an array like this:
$myArray = array(
'emails' => array(
array('email' => 'one#gmail.com','option' => 'test1'),
array('email' => 'two#gmail.com','option' => 'test2'),
)
);
Then:
echo json_encode(myArray);
Using your supllied code, it would be something like this (untested):
$myArray = array();
$i = 0;
$header = array();
while (!feof($handle)) {
$buffer = fgets($handle, $chunk_size);
if (trim($buffer)!='') {
$obj = json_decode($buffer);
$myArray['emails'][] = array('email' => $obj[0],'option' => $obj[2]);
$i++;
}
}
fclose($handle);
echo json_encode($myArray);

$i = 0;
$result = array(); //create a new array
$header = array();
while (!feof($handle)) {
$buffer = fgets($handle, $chunk_size);
if (trim($buffer)!=''){
$obj = json_decode($buffer);
//echo $obj[0]." ".$obj[2]."<br>"; //comment out this line
$result[] = array('email' => $obj[0], 'option' => $obj[2]); //push new obj to the array
$i++;
}
}
fclose($handle);
echo json_encode(array('emails' => $result)); // convert to json format

Related

Mailchimp Api Subscriber Check via php

I am trying to check if an e-mail address a user enters already is in the list of subscribers or not.
This is what I have tried so far:
<?php
$apikey = 'apikey';
$list_id = 'listid';
$chunk_size = 4096; //in bytes
$url = 'http://us14.api.mailchimp.com/export/1.0/list?apikey='.$apikey.'&id='.$list_id;
/** a more robust client can be built using fsockopen **/
$handle = #fopen($url,'r');
if (!$handle) {
echo "failed to access url\n";
} else {
$i = 0;
$header = array();
while (!feof($handle)) {
$buffer = fgets($handle, $chunk_size);
if (trim($buffer)!=''){
$obj = json_decode($buffer);
if ($i==0){
//store the header row
$header = $obj;
} else {
//echo, write to a file, queue a job, etc.
echo $obj[0];
}
$i++;
}
}
fclose($handle);
}
?>
This will return all email subscribers. I am trying to narrow it down to the specific e-mail the user entered, but I am stuck and don't know how to do it?
/** a more robust client can be built using fsockopen **/
$handle = #fopen($url,'r');
if (!$handle) {
echo "failed to access url\n";
} else {
$i = 0;
$header = array();
while (!feof($handle)) {
$buffer = fgets($handle, $chunk_size);
if (trim($buffer)!=''){
$obj = json_decode($buffer);
if ($i==0){
//store the header row
$header = $obj;
} else {
//echo, write to a file, queue a job, etc.
if ($obj[0] == "myemail#gmail.com") { echo "XXXXXXX";} else { }
}
$i++;
}
}
fclose($handle);
}
?>

Group by a column from csv and sum the values from another (PHP)

I have a csv like this:
25/07/2016 3
25/07/2016 4
26/07/2016 4
26/07/2016 1
And the output that i expect, it have to be like this
25/07/2016 7
26/07/2016 5
I want to do this only using PHP.
I have to mention that i am not using mysql and i don't want to.
Is there a solution to do that?
Try something like this. This is just an edited version from this similar post.
$my_file = fopen('file.csv', 'rb');
$my_array = array();
while($row = fgetcsv($my_file)) {
$my_array[$row[0]] += $row[1];
}
"25/07/2016","3"
"25/07/2016","4"
"26/07/2016","4"
"26/07/2016","1"
For e.g. Let's say you have CSV file that contains data as above.
$arr = array();
$handle = fopen("example.csv", "r");
while(!feof($handle))
{
$arrOfCSVLine = fgetcsv($handle);
$date = $arrOfCSVLine[0];
$no = $arrOfCSVLine[1];
if(!array_key_exists($data,$arr))
{
$arr[$date] = $no;
}
else
{
$arr[$date] += $no;
}
}
echo '<pre>';
print_r($arr);
check this code..
$finalOutput = array();
$file = fopen('myCSVFile.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
if(isset($finalOutput[$line[0]])){
$finalOutput[$line[0]] = $line[1] + $finalOutput[$line[0]];
} else {
$finalOutput[$line[0]] = $line[1];
}
}
print_r($finalOutput);

Saving hex data in binary using PHP does not work properly

I am learning PHP and files and I am trying to write some code that put data in a binary file.
here's my code:
Write
<?php
echo "\n\nWRITE: \n\n";
$c = array();
$data = '';
$c['name'] = 'abcdefghijklmnopqrstuvwxyz';
$data .= implode('', $c);
$fp = fopen('test.bin', 'wb');
$len = strlen($data);
echo "\nFILE CONTENT: $data (strlen: $len)\n\n";
for ($i = 0; $i < $len; ++$i) {
$hx = dechex(ord($data{$i}));
fwrite($fp, pack("C", $hx));
}
echo "Last char is: $hx which mean: ";
echo chr(hexdec('7a'));
echo "\n--------------------------------------------\n";
fclose($fp);
Output
FILE CONTENT: abcdefghijklmnopqrstuvwxyz (strlen: 26)
Last char is: 7a which mean: z
Read
<?php
echo "\n--------------------------------------------\n";
echo "\n\nREAD: \n\n";
$fp = fopen('test.bin', 'rb');
$fseek = fseek($fp, 0, SEEK_SET);
if($fseek == -1) {
return FALSE;
}
$data = fread($fp, 26);
$arr = unpack("C*", $data);
$return = '';
foreach($arr as $val) {
$return .= chr(hexdec($val));
}
$n = '';
$arr = array();
$arr['name'] = substr($return, 0, 26);
print_r($arr);
echo "\n--------------------------------------------\n";
Output
Array
(
[name] => abcdefghipqrstuvwxy
)
Where are the missing letters like the z, m, n or o ?
EDIT 6-3-14 7h36 am: I would like to have the .bin file not plain text if possible
You are trying to set HEX chars in a char (C - unsigned char) instruction.
echo "\t";
foreach( array('0x41', 65, 'a') as $o )
echo $o."\t";
echo "\n";
foreach( array('c*','C*','a*','A*','h*','H*','v*','n*','S*') as $o ){
echo $o . "\t";
foreach( array(0x41, 65, "a") as $oo ) {
echo pack($o, $oo);
echo "\t";
}
echo "\n";
}
If you run this, you will see quickly how pack works with the 3 different values of a (HEX, DEC and normal).
You have to use the h instruction to accomplish what you need.
function writeToFile($data) {
$fp = fopen(FILENAME, 'wb');
$len = strlen($data);
for ($i = 0; $i < $len; ++$i) {
$hx = dechex(ord($data[$i]));
$result = fwrite($fp, pack("h*", $hx));
if(!$result) {
// show something
}
}
fclose($fp);
}
Now, for read that data. You will need to use the same one h and split the string you get back (split it using str_split with the parameter 2 since it's HEX 00 = 0 and FF = 255 - assuming you won't go over 255). Since h returns an array with a single element. Once you get your string back, you need to convert the number you get from the ord in the writeToFile using the chr function.
function readFromFile($lenght, $pos = 0) {
$return = '';
$fp = fopen(FILENAME, 'rb');
if(!$fp) {
// show something
}
$fseek = fseek($fp, $pos, SEEK_SET);
if($fseek == -1) {
// show something
}
$data = fread($fp, $lenght);
$data = unpack("h*", $data);
$arr = str_split(current($data), 2);
foreach($arr as $val) {
$return .= chr(hexdec($val));
}
return $return;
}
Now, you create your string and write to the file:
$data = 'This should work properly, thanks for StackOverFlow!';
$len = strlen($data);
writeToFile($data);
Then read back:
echo readFromFile($len);
The content of your file will look like this:
E<86><96>7^B7<86>öWÆF^Bwö'¶^B^G'ö^GV'Æ<97>Â^BG<86>^Væ¶7^Bfö'^B5G^V6¶ôgV'dÆöw^R

php to convert CSV to JSON with nested objects

I have csv file like this:
data,IF,VVS1,VVS2
D,23,17,15
E,17,15,14
What i need is to convert this CSV into JSON but to look like this:
{"D" : {"IF":"23", "VVS1":"17", "VVS2":"15"},"E" : {"IF":"17", "VVS1":"15", "VVS2":"14"}}
Any help?
/* Lets suppose, the csv file is, mydata.scv */
<?php
$mydata = array();
if($file = fopen("mydata.csv","r")){
$csvheaders = fgetcsv($file);
while(($row = fgetcsv($file)) !== FALSE){
$arr = array();
for($i=1; $i<count($csvheaders); $i++){
$arr[$csvheaders[$i]] = $row[$i];
}
$mydata[$row[0]] = $arr;
}
fclose($file);
// encode $mydata array into json to get result in the required format
$mydatainformat = json_encode($mydata);
echo $mydatainformat; // This is your output.
}
?>
Maybe help you, but I recommend add error handling.
<?php
$file = fopen('test.csv', 'r');
$header = fgetcsv($file);
array_shift($header);
$data = array();
while ($row = fgetcsv($file))
{
$key = array_shift($row);
$data[$key] = array_combine($header, $row);
}
echo json_encode($data);
fclose($file);

PHP : POST-- How to replace defined KEY from ARRAY in a file

I'm a bit lost for I'm "green" in PHP.
Please, may you teach me how to fix this:
on 'POST' --> Replace a specified array key from a file:
(WRONG:)
<?php
$newData = $_POST["sendData"];
if(isset($_POST['sendData'])){
$file = fopen('fileToOpen.php', 'a');
foreach($file as $key => $val)
{
$data[$key] = explode("|", $val);
}
for($k = 0; $k < sizeof($file); $k++)
{
unset($data[$k][3]);
}
$data[$k][3] = "$newData";
fwrite($file, $data[$k][3]);
fclose ($file);
}
?>
That's wrong as it continues to write:
data1|data2|data3|oldDatanewData
instead of rewrite:
data1|data2|data3|newData
Is there any other technique to achieve something similar? Perhaps with file_put_contents? Am I missing implode?
Thanks!
Dunno what are you asking for but perhaps you only need to serialize and unserialize the array.
$data_array = unserialize(file_get_contents('fileToOpen.php'));
$data_array[$key_you_want_to_change] = $new_data;
file_put_contents('fileToOpen.php', serialize($data_array));
$newData = $_POST['sendData'];
if(isset($_POST['sendData'])){
$file = "fileToOpen.php";
$oldData = file_get_contents($file);
$oldData = eregi_replace("\n","",$oldData);
$FullDataArray = explode("?",$oldData);
$oldDataArray = explode("|",$FullDataArray[1]);
$oldDataArray[3] = $newData;
$newDataString .= "
foreach($oldDataArray as $key=>$val) {
$newDataString .= $val;
if($key!="3") {
$newDataString .= "|";
}
}
$fh = fopen($file, 'w');
fwrite($fh,$newDataString);
fclose($fh);
}
?>

Categories