So here is the issue. I am pulling a CSV file from an API and need to place it into an array. Here is my current code:
$url = "https://www.*****************";
$myvars = 'username=*********&password=*************';
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text'));
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if(!curl_exec($ch)){
die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
} else {
$response = curl_exec($ch);
$exploded = nl2br($response);
//echo $response."<br>";
var_dump($exploded);
}
curl_close($ch);
The problem is I am getting the response:
string(245) ""Number","Name","Description","Type","Fixed Width Boolean","Quote Character","Delimiter Character","End of Line Sequence","Header Boolean","Column Count"
"1","All Calls","All Call Data","Call","false","None",",","\r\n","true","14"
"
This is two lines in the CSV, but comes out in a single string line. I tried exploding it, but it seems to have two delimiters and I tried splitting it, but it will not find the second delimiter. I want it to generate like this:
array(
"Number" => 1,
"Name" => "All Calls",
"Description" => "All Call Data",
"Type" => "Call",
"Fixed Width Boolean" => false,
"Quote Character" => "None",
"Delimiter Character" => ",",
"End of Line Sequence" => "\r\n",
"Header Boolean" => true,
"Column Count" => 14
);
The first line of the CSV is the headers and the data underneath is the data it needs to align to. Also future requests will have multiple lines of data and they need to match with the headers too. Any ideas?
If you're dealing with CSV, try using the built-in function for such. Then use array_combine to stick your headers in as keys:
$response = curl_exec($ch);
$csv_data = array_map('str_getcsv', explode("\n", $response));
$headers = array_shift($csv_data);
foreach ($csv_data as $v) {
$data[] = array_combine($headers, $v);
}
As an example:
$response = <<< CSV
"Number","Name","Description","Type","Fixed Width Boolean","Quote Character","Delimiter Character","End of Line Sequence","Header Boolean","Column Count"
"1","All Calls","All Call Data","Call","false","None",",","\\r\\n","true","14"
CSV;
$csv_data = array_map('str_getcsv', explode("\n", $response));
$headers = array_shift($csv_data);
foreach ($csv_data as $v) {
$data[] = array_combine($headers, $v);
}
print_r($data);
Output:
Array
(
[0] => Array
(
[Number] => 1
[Name] => All Calls
[Description] => All Call Data
[Type] => Call
[Fixed Width Boolean] => false
[Quote Character] => None
[Delimiter Character] => ,
[End of Line Sequence] => \r\n
[Header Boolean] => true
[Column Count] => 14
)
)
You can also turn your csv string into a file pointer and use fgetcsv on it. Here is an example of how it works:
Josh:~$ php -a
Interactive shell
php > $data = <<<CSV
<<< > "col1","col2"
<<< > "d1",","
<<< > CSV;
php > echo $data;
"col1","col2"
"d1",","
php > $fp = fopen('data://text/plain,' . $data, 'r');
php > while (($row = fgetcsv($fp)) !== false) {
php { var_dump($row);
php { }
array(2) {
[0]=>
string(4) "col1"
[1]=>
string(4) "col2"
}
array(2) {
[0]=>
string(2) "d1"
[1]=>
string(1) ","
}
Using your example it would be similar to the following
$response = <<<CSV
"Number","Name","Description","Type","Fixed Width Boolean","Quote Character","Delimiter Character","End of Line Sequence","Header Boolean","Column Count"
"1","All Calls","All Call Data","Call","false","None",",","\r\n","true","14"
CSV;
$fp = fopen('data://text/plain,' . $response, 'r');
$data = [];
$header = fgetcsv($fp); // first row is column headers
while (($row = fgetcsv($fp)) !== false) {
$data[] = array_combine($header, $row);
}
print_r($data); // list of rows with keys set to column names from $header
/*
Array
(
[0] => Array
(
[Number] => 1
[Name] => All Calls
[Description] => All Call Data
[Type] => Call
[Fixed Width Boolean] => false
[Quote Character] => None
[Delimiter Character] => ,
[End of Line Sequence] =>
[Header Boolean] => true
[Column Count] => 14
)
)
*/
Well, this is a bit "hacky" but it works....
PHP Fiddle
$response = '"Number","Name","Description","Type","Fixed Width Boolean","Quote Character","Delimiter Character","End of Line Sequence","Header Boolean","Column Count","1","All Calls","All Call Data","Call","false","None",",","\r\n","true","14"';
$response = preg_replace('/[,]/', "*", $response);
$response = str_replace('*"*"*', '*","*', $response);
$exploded = explode("*", $response);
$count = count($exploded)/2;
$newArray = [];
for($i=0; $i<$count; ++$i){
$newArray[$exploded[$i]] = $exploded[$i+$count];
}
print_r($newArray);
Which prints
Array
(
["Number"] => "1"
["Name"] => "All Calls"
["Description"] => "All Call Data"
["Type"] => "Call"
["Fixed Width Boolean"] => "false"
["Quote Character"] => "None"
["Delimiter Character"] => ","
["End of Line Sequence"] => "\r\n"
["Header Boolean"] => "true"
["Column Count"] => "14"
)
Related
I'm using a cURL request to grab data from a website and adding them to properties within a loop later. However, I'm stuck on making the data adjustable enough where I can add them directly within the objects.
I have a cURL request that I'm calling that grabbing all the content that I need as below:
public function request()
{
$resource = curl_init();
curl_setopt(
$resource,
CURLOPT_URL,
'lorem ipsum'
);
curl_setopt(
$resource,
CURLOPT_HTTPHEADER,
['API Auth']
);
curl_setopt(
$resource,
CURLOPT_REFERER,
'http://' . $_SERVER['SERVER_NAME'] . '/'
);
curl_setopt(
$resource,
CURLOPT_USERAGENT,
'F'
);
curl_setopt(
$resource,
CURLOPT_RETURNTRANSFER,
1
);
$response = json_decode(curl_exec($resource), true);
if (!curl_errno($resource)) {
$info = curl_getinfo($resource);
echo 'Took ', $info['total_time'], ' seconds to send a request to ', $info['url'], "\n";
};
return $response;
}
When I call the following execution $offices_array = $this->request(); print_r2($offices_array);, this is the return that I receive:
Array
(
[paginator] => Array
(
[total] => 131
[per_page] => 500
[current_page] => 1
[last_page] => 1
[prev_page] =>
[next_page] =>
)
[data] => Array
(
[0] => Array
(
[id] => 1
[name] => Atlanta
)
I'm using this function _csv_to_array:
private function _csv_to_array($filepath) {
$data_array = array();
if(is_readable($filepath)) {
$fp = fopen($filepath, 'r');
while(($data_item = fgetcsv($fp, 1000, "\t")) !== false) {
$data_array[] = array_map('utf8_encode', $data_item);
}
fclose($fp);
}
return $data_array;
}
to print out data as this:
Array
(
[0] => Array
(
[0] => ABU DHABI
[1] => FHI
)
How could I do something similar with the cURL request?
I have excel file that have more than URL, its look like 2000 URL.
I need to check this URL, If URL redirect to: https://example.com/Home/Index remove it from file.
The structure of URL is like:
https://example.com/39188
I see this code but i need it for checking from file
$urls = array(
'http://www.apple.com/imac',
'http://www.google.com/'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
foreach($urls as $url) {
curl_setopt($ch, CURLOPT_URL, $url);
$out = curl_exec($ch);
// line endings is the wonkiest piece of this whole thing
$out = str_replace("\r", "", $out);
// only look at the headers
$headers_end = strpos($out, "\n\n");
if( $headers_end !== false ) {
$out = substr($out, 0, $headers_end);
}
$headers = explode("\n", $out);
foreach($headers as $header) {
if( substr($header, 0, 10) == "Location: " ) {
$target = substr($header, 10);
echo "[$url] redirects to [$target]<br>";
continue 2;
}
}
echo "[$url] does not redirect<br>";
}
How can do it ...
I thinks so:
Step 1: Find lib read and write Excel File in PHP
Step 2: reading file excel -> URL array
Step 3: Create method common: checkingUrl(url) return true/false
Step 3: Create array: existArray
Step 4: loop array (step 2) call method checkingUrl(url)
IF False (URL redirect) -> push url to existArray
Step 5: write file excel with data existArray
Read XLSX (Excel 2003+)
https://github.com/shuchkin/simplexlsx
if ( $xlsx = SimpleXLSX::parse('book.xlsx') ) {
print_r( $xlsx->rows() );
} else {
echo SimpleXLSX::parseError();
}
Output
Array (
[0] => Array
(
[0] => ISBN
[1] => title
[2] => author
[3] => publisher
[4] => ctry
)
[1] => Array
(
[0] => 618260307
[1] => The Hobbit
[2] => J. R. R. Tolkien
[3] => Houghton Mifflin
[4] => USA
)
)
Write FILE
header("Content-Disposition: attachment; filename=\"demo.xls\"");
header("Content-Type: application/vnd.ms-excel;");
header("Pragma: no-cache");
header("Expires: 0");
$out = fopen("php://output", 'w');
foreach ($array as $data)
{
fputcsv($out, $data,"\t");
}
fclose($out);
You need the file()-function:
$urls = file('urls.txt');
I want to send complex Post data with Curl.
The data i try to send:
Array
(
[test] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[file] => CURLFile Object
(
[name] => H:\wwwroot\curl/upload.txt
[mime] =>
[postname] =>
)
)
I need to use the variables in the post-side as $_POST["test"] and $_FILES["file"]
But i can not realize that. For the (sometimes multidimensional) array-data i need http_build_query but that breaks the file. If i don`t use http_build_query my array gives an "array to string conversion" error.
How can i get this to work?
Code:
Index.php
$curl = curl_init();
$postValues = Array("test" => Array(1,2,3));
$postValues["file"] = new CurlFile(dirname(__FILE__). "/upload.txt");
curl_setopt($curl, CURLOPT_URL, "localhost/curl/post.php");
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postValues);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$curlResult = curl_exec($curl);
$curlStatus = curl_getinfo($curl);
echo $curlResult;
post.php
print_r($_REQUEST);
print_r($_FILES);
After very long research to manage the same problem, I think that a simpler solution could be:
$postValues = Array("test[0]" => 1, "test[1]" => 2, "test[2]" => 3);
this is the right way to emulate what happen on browsers
<input type="hidden" name="test[0]" value="1">
<input type="hidden" name="test[1]" value="2">
...
The result is:
Array
(
[test] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
Array
(
[file] => Array
(
[name] => upload.txt
[type] => application/octet-stream
[tmp_name] => /tmp/phprRGsPU
[error] => 0
[size] => 30
)
)
After long research and testing i`ve got the (not very nice but working) solution:
function createHttpHeader($postValues, $overrideKey = null) {
global $delimiter;
// invalid characters for "name" and "filename"
$disallow = array("\0", "\"", "\r", "\n");
$data = Array();
if (!is_array($postValues)) {
$postValues = Array($postValues);
}
foreach($postValues as $key => $value) {
$useKey = $overrideKey === null ? $key : $overrideKey. "[$key]";
$useKey = str_replace($disallow, "_", $useKey);
if (is_array($value)) {
$data = array_merge($data, addPostData($value, $useKey));
} else {
$data[] = "--". $delimiter. "\r\n";
$data[] = "Content-Disposition: form-data; name=\"". $useKey. "\"";
if (is_a($value, "\CurlFile")) {
$data[] = "; filename=\"". basename($value->name). "\"\r\n";
$data[] = "Content-Type: application/octet-stream\r\n\r\n";
$data[] = file_get_contents($value->name). "\r\n";
} else {
$data[] = "\r\n\r\n". $value. "\r\n";
}
}
}
return $data;
}
Test with:
$postValues = Array(
"blaat" => 1,
"test" => Array(1,2,3),
"grid" => Array(0 => array(1,2), 1 => array(4,5)),
"gridComplex" => Array("rows" => array(1,2), "columns" => array(0 => array(1,2,3,4), 1 => array(4,5,4,5)))
);
$postValues["file[0]"] = new CurlFile($file, "text/plain");
$postValues["file[1]"] = new CurlFile($file, "text/plain");
// print_r(new CurlFile($file));exit;
$delimiter = "-------------" . uniqid();
$data = createHttpHeader($postValues);
$data[] = "--" . $delimiter . "--\r\n";
$data = implode("", $data);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "localhost/curl/post.php");
curl_setopt($curl, CURLOPT_HTTPHEADER , array('Content-Type: multipart/form-data; boundary=' . $delimiter, 'Content-Length: ' . strlen($data)));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$curlResult = curl_exec($curl);
echo $curlResult;
Edit: addition the addPostData function:
function addPostData($postValues, $delimiter, $overrideKey = null) {
// invalid characters for "name" and "filename"
$disallow = array("\0", "\"", "\r", "\n");
$data = Array();
if (!is_array($postValues)) {
$postValues = Array($postValues);
}
foreach($postValues as $key => $value) {
$useKey = $overrideKey === null ? $key : $overrideKey. "[$key]";
$useKey = str_replace($disallow, "_", $useKey);
if (is_array($value)) {
$data = array_merge($data, $this->addPostData($value, $delimiter, $useKey));
} else {
$data[] = "--". $delimiter. "\r\n";
$data[] = "Content-Disposition: form-data; name=\"". $useKey. "\"";
if (is_a($value, "\CurlFile")) {
$data[] = "; filename=\"". basename($value->postname). "\"\r\n";
$data[] = "Content-Type: ". $value->mime. "\r\n\r\n";
$data[] = file_get_contents($value->name). "\r\n";
} else {
$data[] = "\r\n\r\n". $value. "\r\n";
}
}
}
return $data;
}
I need to interpret the array received from a remote licensing.
I am calling the remote api via curl and the answer in the browser is:
The parsed answer from curl done by using:
parse_str(curl_exec($ch), $parsed);
print_r($parsed);
is exactly as here:
Array ( [{"success":true,"uses":154,"purchase":{"id":"GYFt6sW7hbURSVdSpipb5g] => =","created_at":"2015-06-06T16:44:41Z","email":"askolon11#gmail.com","full_name":"daniel","variants":"","custom_fields":[],"product_name":"Direkt 1.2","subscription_cancelled_at":null,"subscription_failed_at":null}} )
I tried already for several hours to get the "success" item so later on to check it if it is true or false.
I used
while (list($var, $val) = each($parsed)) {
print "$var is $val\n";
}
but the result is the same.
Also I tried:
$parsed[0]['success'] or $parsed[0]['success']
and no result as well.
My full code is:
<?php $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.gumroad.com/v2/licenses/verify");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
$data = array( 'product_permalink' => 'skQsA', 'license_key' => 'AB26AD9D-1B3B42E0-92356540-CF4E7C1B' );
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
$output = array();
parse_str(curl_exec($ch), $parsed);
print_r($parsed); // HERE WE HAVE THE ARRAY
while (list($var, $val) = each($parsed)) {
// print "$var is $val\n";
}
curl_close($ch);
?>
Thank you.
The API seems to return a JSON encoded string. So instead of:
parse_str(curl_exec($ch), $parsed);
use:
$parsed = json_decode(curl_exec($ch), true);
Then a print_r($parsed) will output:
Array
(
[success] => 1
[uses] => 154
...
)
And for checking success value:
if ($parsed['success']) {
// Do stuff
}
Instead of doing
$parsed[0]['success'];
try just
$parsed['success'];
If the array you are getting back is an associative array, then the 'key' will be the word 'success'.
$parsed = [
"success" => true,
"uses" => 154,
"purchase" =>
[
"id" => "GYFt6sW7hbURSVdSpipb5g] => =",
"created_at" => "2015-06-06T16:44:41Z",
"email" => "askolon11#gmail.com",
"full_name" => "daniel",
"variants" => "",
"custom_fields" => [],
"product_name" => "Direkt 1.2",
"subscription_cancelled_at" => null,
"subscription_failed_at" => null
]];
if($parsed['success'])
echo 'true';
else
echo 'false';
I'm working on a project and trying to find a way to add my api results to mysql.
Here is the page were you can find the results.
Here is the code of the page:
<?php
///PLOT PROJECT USER REQUEST
//HELPER FUNCTION TO PRINT TO CONSOLE
function debug_to_console( $data ) {
if ( is_array( $data ) )
$output = "<script>console.log( 'Debug Objects: " . implode( ',', $data) . "' );</script>";
else
$output = "<script>console.log( 'Debug Objects: " . $data . "' );</script>";
echo $output;
}
//PLOT PROJECT REQUEST
$appId = '9fed0c75ca624e86a411b48ab27b3d5a';
$private_token = 'VGjPehPNBa5henSa';
$qry_str = "/api/v1/account/";
$ch = curl_init();
$headers = array(
'Content-Type:application/json',
'Authorization: Basic '. base64_encode($appId.":".$private_token) // <---
);
$geofenceId = '736cb24a1dae442e943f2edcf353ccc7';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, 'https://admin.plotprojects.com/api/v1/notification/?geofenceId=' . $geofenceId);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
$content = trim(curl_exec($ch));
curl_close($ch);
print $content;
?>
You can use json_decode() to decode your JSON string and take the values that you need to make your query. Read more at:
http://php.net/manual/en/function.json-decode.php
<?php
//The response from http://www.jobsinsac.com/api/api_notification.php
$json = '{ "success": true, "result": { "data": [{ "placeId": "736cb24a1dae442e943f2edcf353ccc7", "cooldownDays": 0, "triggerTimes": "inherit", "state": "published", "cooldownSeconds": 1, "data": "http://www.illuminatimc.com", "enabled": true, "geofenceId": "736cb24a1dae442e943f2edcf353ccc7", "id": "0cad6b54d225459e85cd8c27567f8b0b", "message": "Get a cold beer, for $2.00, shots for $4.00, come inside, up stairs.", "created": "2015-03-17T18:54:41Z", "timespans": [], "handlerType": "landingPage", "trigger": "enter" }], "total": 1 } }';
$data = json_decode($json, true);
print_r($data);
?>
Output:
Array
(
[success] => 1
[result] => Array
(
[data] => Array
(
[0] => Array
(
[placeId] => 736cb24a1dae442e943f2edcf353ccc7
[cooldownDays] => 0
[triggerTimes] => inherit
[state] => published
[cooldownSeconds] => 1
[data] => http://www.illuminatimc.com
[enabled] => 1
[geofenceId] => 736cb24a1dae442e943f2edcf353ccc7
[id] => 0cad6b54d225459e85cd8c27567f8b0b
[message] => Get a cold beer, for $2.00, shots for $4.00, come inside, up stairs.
[created] => 2015-03-17T18:54:41Z
[timespans] => Array
(
)
[handlerType] => landingPage
[trigger] => enter
)
)
[total] => 1
)
)