Script to exctract data from CSV and generate http_build_query - php

I am trying to pull data out of a CSV file and generate a http_build_query to submit as a http post
My data looks like this:
First,Last,Address,City,St,Zip,email,phone,dob,optindate,ipaddress,url
Abbey,Johnson,4004 S. Parker Dr. 206,Sioux Falls,SD,55106,abbey#email.com,6053451657,06/18/1924,4/19/2008 11:58:34,12.174.252.216,http://www.ecoupons.com/
My code looks like this:
<?PHP
$file_handle = fopen("test.2", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
$data = array('firstname' => "$line_of_text[0]",
'lastname' => "$line_of_text[1]",
'address' => "$line_of_text[2]",);
echo http_build_query($data) . "\n";
}
fclose($file_handle);
?>
My result is:
firstname=Abbey&lastname=Johnson&address=4004+S.+Louise+Ave.+206
firstname=&lastname=&address=
I am not sure why the second line without the data is created and how do I keep the white spaces in the array data?
Thanks!

Your CSV does does seem to be valid or readable (can't see the new line ) so i use a simple of mine
Your address contains , which affects the way fgetcsv reads the file
Try
$fp= fopen("log.txt", "r");
while (!feof($fp) ) {
list($firstname,$lastname,$address) = fgetcsv($fp);
$data = array('firstname' => $firstname,
'lastname' => $lastname,
'address' => $address);
echo http_build_query($data) . PHP_EOL;
}
Output
firstname=Abbey&lastname=Johnso&address=4004+S.+Louise+Ave.+206

Related

I don't manage to parse properly a CSV file with "|" delimeter using PHP

I'm trying to parse a CSV file.
<?php
$url = 'https://flux.netaffiliation.com/feed.php?maff=3E9867FCP3CB0566CA125F7935102835L51118FV4';
$csv = array_map('str_getcsv', file($url), ["|"]);
echo '<pre>'; echo print_r ($csv); echo '</pre>';
?>
Here is a sample of what i get :
[1] => Array
(
[0] => 5016488133494|Ary And The Secret Of Seasons PS4|100001|9.99||Jeu > PS4|https://xht.micromania.fr/?P3CB0566CA125FS1UD41282b0253295V4|https://edge.disstg.commercecloud.salesforce.com/dw/image/v2/BCRB_STG/on/demandware.static/-/Sites-masterCatalog_Micromania/default/dw65159733/images/high-res/100001.jpg?sw=1000|JUST FOR GAMES|JUST FOR GAMES|Explorez le monde merveilleux de Valdi !||new|4.99|||||||2
)
Apparently, the parser doesn't take every "|" into account.
If you inspect your output, you'll notice that the split works on your first row. This is because (oddly) PHP only uses the extra args once per iteration, so you'd need to specify them for each row:
array_map('str_getcsv', file($url), ["|", "|", "|", ...]);
... which makes not a whole lot of sense to me, as you don't know how many rows you have. I'd just call it explicitly like this instead:
$csv = array_map(fn($line) => str_getcsv($line, '|'), file($file));
Or the older style:
$csv = array_map(function($line) { return str_getcsv($line, '|'); }, file($file));
Here's a script I suggest. It assembles csvArray as result, I hope you'll handle further:
<?php
$url='https://flux.netaffiliation.com/feed.php?maff=3E9867FCP3CB0566CA125F7935102835L51118FV4';
$file_name = 'csvToParse.csv';
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
file_put_contents($file_name, file_get_contents($url, false,
stream_context_create($arrContextOptions)));
$fopenCSVHandle=fopen($file_name, 'r');
$csvArray=array();
if ($fopenCSVHandle !== false){
while (($data = fgetcsv($fopenCSVHandle, 1000, "|")) !== FALSE) {
//echo('<br />single row $data=<br />');
//print_r($data);
$csvArray[]=$data;
}
//echo('<br />We got this $data from CSV:<br />');
//print_r($csvArray);
}
?>

I'm writing json array to file. I'm getting [{ , , }][{ , , }][{ , , }]. I need this output [{ , , },{ , , },{ , , }]. Any Suggestions?

I'm writing json array to the file. I'm getting [{ , , }][{ , , }][{ , , }]. I need this output [{ , , },{ , , },{ , , }].
I'm not adding json items to the array, instead creating multiple arrays.
$a = array();
$new_data = array(
'name' => $_POST["product_name"],
'age' => $_POST["quantity_stock"],
'city' => $_POST["item_price"]
);
// pushing the post data each time the page reloads with post values
array_push($a,$new_data);
$json = json_encode($a);
$myfile = fopen("newfile.json", "a+") or die("Unable to open file!");
fwrite($myfile, $json);
fclose($myfile);
$data = file_get_contents("newfile.json");
$data = json_decode($data, true);
//output
[{"name":"ggg","qty":"ff","price":"ff"}]
[{"name":"ggg","qty":"ff","price":"ff"}]
//How to achieve this
[{"name":"ggg","qty":"ff","price":"ff"},
{"name":"ggg","qty":"ff","price":"ff"}]
I think you are write to the file after each post request and your array $a will only have the post array data.
that's why you getting your file at the end look like that
//output
[{"name":"ggg","qty":"ff","price":"ff"}]
[{"name":"ggg","qty":"ff","price":"ff"}]
so to fix this issue and get your data in the right format , each time you want to write to your file , first you need to load the data from the file and then merge it to your array $a and then write it again.
so this code should works in your case
//load file data
$data = file_get_contents("newfile.json");
$a = json_decode($data, true);
$new_data = array(
'name' => $_POST["product_name"],
'age' => $_POST["quantity_stock"],
'city' => $_POST["item_price"]
);
// pushing the post data each time the page reloads with post values
array_push($a,$new_data);
$json = json_encode($a);
$myfile = fopen("newfile.json", "w+") or die("Unable to open file!");
fwrite($myfile, $json);
fclose($myfile);
$data = file_get_contents("newfile.json");
$data = json_decode($data, true);
I initialized $a with the data in file and change mode in fopen to w+
Try loading the data from the file into a, appending new_array to said data, then writing this new json list object into the file.
Managed to merge this together. There is most likely a better solution
array_merge in official PHP documentation
json_decode in official PHP documentation
$a = [{"name":"ggg","qty":"ff","price":"ff"}];
$b = [{"name":"ggg","qty":"ff","price":"ff"}];
json_encode(array_merge(json_decode($a, true),json_decode($b, true)))
or
$r = [];
foreach(json_decode($a, true) as $key => $array){
$r[$key] = array_merge(json_decode($b, true)[$key],$array);
}
echo json_encode($r);
use below code, hope it will meet your output:
$data = file_get_contents("newfile.json");
$a = explode("][", $data);
$x = '';
foreach($a as $y){
$x .= $y.",";
}
echo trim($x, ",");
There problem is with the appending data to newfile.json, Here a list already appended as a text, and after that whenever we append more text, it is appended as a text, not a json object, Therefore kindly try the following code along with your existing code:-
$a = array();
$new_data = array(
'name' => $_POST["product_name"],
'age' => $_POST["quantity_stock"],
'city' => $_POST["item_price"]
);
// reading data from .json file
$data = file_get_contents('newfile.json');
// creating an array of object from the text of .json file
$tempArray = json_decode($data);
// adding our new object to array
array_push($tempArray, $new_data);
// creating json representation of the array
$jsonData = json_encode($tempArray);
// writing json representation to the .json file
file_put_contents('newfile.json', $jsonData);
Hope this will help.
$a = array();
$new_data = array(
'name' => $_POST["product_name"],
'age' => $_POST["quantity_stock"],
'city' => $_POST["item_price"]
);
// pushing the post data each time the page reloads with post values
$data = file_get_contents("newfile.json");
$data = json_decode($data, true);
$lastIndex = count($data);
$data[$lastIndex] = $new_data;
$myfile = fopen("newfile.json", "w") or die("Unable to open file!");\
fwrite($myfile, json_encode($data));
fclose($myfile);
$data = file_get_contents("newfile.json");
$data = json_decode($data, true);
print_r($data);

PHP writes null to JSON file

I've seen similar posts to this question but I can't seem to figure it out. I have a small PHP script that reads and writes form input to a JSON file, like this –
$file = 'data.json';
$arr_data = array();
$formdata = array(
'name' => strip_tags( trim($_POST['formName']) ),
'email' => $email,
'phone' => strip_tags( trim($_POST['formPhone']) ),
'message' => strip_tags( trim($_POST['formMessage']) )
// also tested this just using reg strings
);
$jsondata = file_get_contents($file);
//var_dump($jsondata); returns whatever string content is in the file, so seems to work
$arr_data = json_decode($jsondata, true);
array_push($arr_data, $formdata);
//var_dump($arr_data); returns NULL, not sure what happens here
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
file_put_contents($file, $jsondata);
Any ideas? Using PHP 5.5.9, checked that files are writeable. Both files have UTF8 encoding.
json_decode() will return NULL if the input is blank. Try this to ensure your $arr_data is an array...
$arr_data = json_decode($jsondata, true);
if ($arr_data === null) {
$arr_data = [];
}
maybe you want this code
<?php
$file = 'data.json';
$email='your mail info';
$arr_data = array();
$formdata = array(
'name' => strip_tags( trim($_POST['formName']) ),
'email' => $email,
'phone' => strip_tags( trim($_POST['formPhone']) ),
'message' => strip_tags( trim($_POST['formMessage']) )
// also tested this just using reg strings
);
$jsondata = file_get_contents($file);
//var_dump($jsondata); returns whatever string content is in the file, so seems to work
$arr_data = json_decode($jsondata, true);
// I added for if data.json is null to empty array
$arr_data = is_null($arr_data)?array():$arr_data;
array_push($arr_data, $formdata);
//var_dump($arr_data); returns NULL, not sure what happens here
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
file_put_contents($file, $jsondata);
?>
others
you should change your code to keep post data not null or default values and pay attention to file_get_contents method about file length

Create multiple files from one file

foreach($new_files as $new_file) {
//create file
$myfile = fopen($filename, "w");
//put contents in the file
fwrite($filename, $new_file['content']);
//close the file
fclose($myfile);
}
I have this code to create a new file, I want to be able to open $filename, and create multiple files from it, with the content of new_file.
This code doesn't seem to work,all I get is one new empty file, any ideas?
Here is a working example.
You have to store data in standard structure like JSON in $filename, then read its data and make other files.
<?php
// $Data = file_get_contents($filename);
// $Data = json_decode($Data); <--- if stored as json
// Sample Data
$Data = [
[
'name' => 'file1.txt',
'content' => 'content1',
],
[
'name' => 'file2.txt',
'content' => 'content2',
],
];
foreach ($Data as $Row) {
$File = fopen($Row['name'], 'w');
fwrite($File, $Row['content']);
fclose($File);
}

Receive API application/octet-stream Post via PHP

I have post that comes from an iOS device. The header is that of:
application/octet-stream
I am trying to figure out in PHP how to receive that file. $_FILES seems to only work for:
multipart/form-data
Here is what we use to do:
if(isset($_FILES['media'])){
$this->load->library( 'lib_files' );
ini_set('max_execution_time', 300);
$parts = pathinfo( $_FILES['media']['name'] );
$result = $this->lib_files->move_file_into_structure( array(
'project_id' => $project_id
, 'current_path' => $_FILES['media']['tmp_name']
, 'original_name' => $parts['filename']
, 'extension' => $parts['extension']
, 'insert_for' => 'mobile_journal_id'
, 'insert_for_id' => $journal_id
, 'user_id' => $user_project->user_id
) );
But now I am trying to grab octet-stream binary upload and I am confused how to do that here. So far I think I have to do something like this:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if($_POST == null) {
$handle = fopen('php://input', 'r');
$rawData = fgets($handle);
}
}
That rawData should be my file correct? How do I grab things like original_name, extension, current path I take it is php://input. I have never used octet-stream and I found nothing really online about doing it for php.

Categories