Extract parts of a php array to client side - php

So I'm trying to centralize products in one central php file and have my client side php just request info so I only have to edit the central php file to add and remove products
my server side
$varProduct= (
// [0] [1] [2] [3 4 5 6 7] [8]
array("Title" , 0001 , 100, 0,0,1,1,0, "/womens/tops/s/2.png", "/womens/tops/s/2.jpg", "/womens/tops/s/2.jpg", 50 )
)
In my html client side I want to display the title, the price [2] and the url [8]
basically
for(i=o, i< $varProduct.length(), i++){
//display $varProduct[i][0];
//display the Image for $varProduct[i][8];
//display $varProduct[i][2];
}
how can I put values in my server side file to my client side in within html tags? I need to display them inline will I be able to format the variables?

Try something like this
<?php
for ($i = 0; $i < count($varProduct); $i++) {
//full path -- then post pram
$return = sendPostData("http://stackoverflow.com/", array('parm1' => $varProduct[$i][0], 'parm2' => $varProduct[$i][0]));
print_r($return);
}
?>
<?php
//send data function
function sendPostData($url, Array $post) {
$data = "";
foreach ($post as $key => $row) {
$row = urlencode($row); //fix the url encoding
$key = urlencode($key); //fix the url encoding
if ($data == "") {
$data .="$key=$row";
} else {
$data .="&$key=$row";
}
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$result = curl_exec($ch);
curl_close($ch); // Seems like good practice
return $result;
}
?>

Related

PHP API request by GET details

I'm trying to get the details from this example (i created the code right now).
But i'm very... confused... how can i get the details of the link, then separate and send to my MYSQL database..
<?php
$ch = curl_init();
$url = "https://reqres.in/api/users?page=2";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resp = curl_exec($ch);
if($e = curl_error($ch)) {
echo $e;
}
else {
$decoded = json_decode($resp, true);
//print_r($decoded);
foreach($decoded as $key => $item) {
$array = array(
'id' => ,
'email' => ,
'first_name' => ,
'last_name' => ,
);
print_r($array);
}
}
curl_close($ch);
?>
If you call the url in your browser then you will see that the result array is present in the data field.
You may check this by printing the whole result:
print_r($decoded);
So if you like to print_r the results it should be simply
print_r($decoded['data']);
If you like to store it in your database you may walk through the array and store each item
foreach($decoded['data'] as $item) {
storeItem($item);
}
To make this work you should implement the storeItem function which accepts the array $item and stores it into your database. There are various tutorials about doing that.

Edit and redirect a post request with json

For my project, i'm trying to get the post request on my index.php, edit it with some random values, and then redirect it to another page.
I tried the following:
----------- POST REQUEST -----------
Array
(
[authToken] => 0a65e943412453ecec35c814
[sessionId] => 431503466924
[answers] => [{"Boost":false,"answerTime":1300,"id":3},{"Boost":false,"answerTime":800,"id":1},{"Boost":false,"answerTime":900,"id":3},{"Boost":false,"answerTime":1000,"id":1},{"Boost":false,"answerTime":1200,"id":1}]
[userId] => 2235
)
----------- POST REQUEST -----------
My index.php
<?php
$time=[800,900,1000,1100,1200,1300,1500];
$array = json_decode($_POST['answers'], true);
foreach($array as &$k)
{
$k['answerTime'] =$time[array_rand($time)];
}
$postpop = json_encode($array);
$url = 'http://127.0.0.1/index2.php';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($postpop));
curl_setopt($ch,CURLOPT_POSTFIELDS,$postpop);
$result = curl_exec($ch);
curl_close($ch);
?>
By doing that, i only get the [answers] on my response.
How can i get to recompile the full request?
It looks like you are simply failing to reassemble all the parts. Store the POST, manipulate the answer element, and then replace that part.
<?php
$time = [800,900,1000,1100,1200,1300,1500];
//Store the full post as received.
$originalPost = $_POST;
$array = json_decode($_POST['answers'], true);
foreach($array as &$k) {
$k['answerTime'] = $time[array_rand($time)];
}
//replace just the part of the array we manipulated
$originalPost['answers'] = json_encode($array);
$url = 'http://127.0.0.1/index2.php';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($originalPost));
curl_setopt($ch,CURLOPT_POSTFIELDS,$originalPost);
$result = curl_exec($ch);
curl_close($ch);

Instagram API - How to check last page last record?

I am working on Instagram API first time and also using social media API first time so I have very basic knowledge of how to call and read data from API. So I have created one recursive function to call next page and read data. Now I am storing Media ID, Comments Counts, Likes Counts for each and every post data with next page in my instagram database table. Now I want to insert one another record to my schedule table when API reached to last page and inserted all records to instagram table. I am adding my code below and I will happy if someone guide me to make code more proper :)
My Code Work:
public function User($next=null){
global $TotalHashTagPosts; // Total hashtag post counts
global $CommentsSum; // Sum of comments
global $LikesSum; // Sum of likes
$AccessToken = ACCESS_TOKEN;
$url = "https://api.instagram.com/v1/users/481959735/media/recent/?access_token=".$AccessToken;
if($url !== null) {
$url .= '&max_tag_id=' . $next;
}
$Ch = curl_init();
curl_setopt($Ch, CURLOPT_URL, $url);
curl_setopt($Ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($Ch, CURLOPT_TIMEOUT, 20);
curl_setopt($Ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($Ch, CURLOPT_SSL_VERIFYPEER, 0);
$Result = curl_exec($Ch);
curl_close($Ch);
$Result = json_decode($Result);
if(isset($Result->data)){
$Data = $Result->data;
for($i=0; $i<count($Data); $i++){
if(empty($Data)){
continue;
}
$LikesSum = $Data[$i]->likes->count; // Get likes total per media
$CommentsSum = $Data[$i]->comments->count; // Get comments total per media
$InstagramId = $Data[$i]->user->id; // Get media instagrammer id
$MediaId = $Data[$i]->id; // Get media id
$data = array(
'instagram_id' => $InstagramId,
'media_id' => $MediaId,
'comments_count' => $CommentsSum,
'likes_count' => $LikesSum,
'created_date' => date(DATE_YYYYMMDDHMS_24),
'status' => '1'
);
$this->db->insert('instagrammer_table', $data);
if($this->db->affected_rows() > 0){
echo "Insert successful";
}else{
echo "Failed to insert record";
}
}
if(isset($Result->pagination->next_url) && !empty($Result->pagination->next_url)){
$next = $Result->pagination->next_url;
$this->User($next);
}else{
$NextUrl = "";
}
}
}

Write Array to File:PHP

I'm trying to write the array $jsonDataInArray to an external csv file. Right now, my file only has the column headers without the data underneath. Could someone help me step through this PHP array, $jsonDataInArray, and write it to an external .csv file?
//set url for pipedrive data being pulled
$api_token="soemToken";
$url = "https://someURL.com;
$ch = curl_init(); //initialize connection with a URL
//check if cURL is enabled or not
if(is_callable('curl_init'))
{
echo "curl_init Enabled";
}
else
{
echo "curl_init Not enabled";
}
echo '<br/><br/><br/><br/><br/><br/>';
curl_setopt($ch, CURLOPT_URL, $url); //fetching URL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //return queried data as string
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);//verify certificate
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);//check the existence of a common name & verify that it matches the hostname provided
curl_setopt ($ch, CURLOPT_CAINFO, dirname(__FILE__)."/permissingFile.pem");//name of file holding certificates to verify peer with
$json_response = curl_exec($ch);//perform cURL session. Returns ALL of JSON data if sucessful, false if not.
$info = curl_getinfo($ch);//gets array of info about cURL transfer.
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);//gets HTTP message about cURL transfer
if ( $status != 200 )
{
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($ch) . ", curl_errno " . curl_errno($ch));
//die();
}
curl_close($ch);//close connection with URL
// create an array from the data that is sent back from the API
$response = json_decode($json_response, 1);
// Gets the count of records returned from the api. Used in the for loop to go through response 1 array element at a time.
$count = Count($response['data']);
for ($x=0; $x<$count; $x++)
{
$currentRecord = $response['data'][$x];
$jsonDataInArray = array
(
"id" => $response['data'][$x]['id'],
"user_id" => $response['data'][$x]['user_id']['id'],
"person_id" => $response['data'][$x]['person_id']['value'],
"org_id" => $response['data'][$x]['org_id']['value'],
"stage_id" => $response['data'][$x]['stage_id'],
"title" => $response['data'][$x]['title'],
"value" => $response['data'][$x]['value'],
"currency" => $response['data'][$x]['currency'],
"add_time" => $response['data'][$x]['add_time'],
"update_time" => $response['data'][$x]['update_time'],
"stage_change_time" => $response['data'][$x]['stage_change_time'],
"active" => $response['data'][$x]['active'],
"deleted" => $response['data'][$x]['deleted'],
"status" => $response['data'][$x]['status'],
);
ksort($currentRecord);
}
$test_array = $response['data'][0];//test_array = first row of data
if($startPos == 0){
$fp = fopen('cacheDeals3.csv', 'w');
fputcsv($fp, array_keys($response['data'][0]));
}else{
$fp = fopen('cacheDeals3.csv', 'a');
}
foreach ($jsonDataInArray as $fields)
{
fputcsv($fp, $fields);
}
$jsonDataInArray is being overwritten on every iteration of the for loop, therefore fputcsv is being passed a string as the $field parameter rather than an array.
You need to append a new array to $jsonDataInArray each time, change
$jsonDataInArray = array
to
$jsonDataInArray[] = array

post data to api using json

This code i wrote to send data to an api using post method in JSON but in response i am getting invalid can anyone tell me what is wrong in the code.
$post = array(
"operatorCode"=>"9",
"scheduleCode"=>"84W92XC8LOBAF3KZP4",
"travelDate"=>"2015-03-20",
"fromStationCode"=>"84",
"toStationCode"=>"76",
"boardingPointCode"=>"191933",
"droppingPointCode"=>"0000",
"email"=>"*********",
"mobile"=>"*******",
"passenger"=>array(
"seatNumber"=>"40",
"name"=>"*****",
"age"=>"20",
"gender"=>"Male"
)
);
$data_string = json_encode($post);
echo $data_string;
$ch=url_init('http://api?username=*****');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS,array('data'=>$data_string));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$result = json_decode($result);
var_dump($result);
echo'<pre>';
print_r($result);
Response From api
stdClass Object
(
[code] => 0
[errorCode] => ER30
[errorDesc] => Invalid Data
[message] => Failure
)
Sample URL:
http://<ServerName>/bookbustickets/rest/json/2.0/tempbooking?username=****&password‌​=******
Sample Input data:
data={"operatorCode":"2586",
"scheduleCode":"7Q52586C3YG8KJ350F2F5V264",
"travelDa‌​te":"2015-03-10",
"fromStationCode":"76",
"toStationCode":"75",
"boardingPointCode":‌​"284936",
"droppingPointCode":"0000",
"email":"test#gmail.com",
"mobile":"9876543210‌​",
"passenger":[
{
"seatNumber":"3",
"na 9 me":"Test",
"age":20,
"gender":"Male"},
{
"seatNumber":"4",
"name":"Test",
"age":20,
"g‌​ender":"Male"}
]
}
Ok so the problem is that "passenger" should be an array of objects so try changing your code to
$passenger1 = new stdClass();
$passenger1->seatNumber = "40";
$passenger1->name = "*****";
$passenger1->age = "20";
$passenger1->gender = "Male";
$passenger2 = new stdClass();
$passenger2->seatNumber = "41";
$passenger2->name = "*****";
$passenger2->age = "21";
$passenger2->gender = "Female";
$post = array(
"operatorCode"=>"9",
"scheduleCode"=>"84W92XC8LOBAF3KZP4",
"travelDate"=>"2015-03-20",
"fromStationCode"=>"84",
"toStationCode"=>"76",
"boardingPointCode"=>"191933",
"droppingPointCode"=>"0000",
"email"=>"*********",
"mobile"=>"*******",
"passenger"=>array( $passenger1, $passenger2 )
);
This will generate the following result
{
"operatorCode":"9",
"scheduleCode":"84W92XC8LOBAF3KZP4",
"travelDate":"2015-03-20",
"fromStationCode":"84",
"toStationCode":"76",
"boardingPointCode":"191933",
"droppingPointCode":"0000",
"email":"*********",
"mobile":"*******",
"passenger":[
{
"seatNumber":"40",
"name":"*****",
"age":"20",
"gender":"Male"
},
{
"seatNumber":"41",
"name":"*****",
"age":"21",
"gender":"Female"
}
]
}
Also I am note sure why you are using
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
Would not
curl_setopt($ch, CURLOPT_POST, true);
be a better option?

Categories