I have the following text that I want to strip out and grab the data.
(function() {})({
"Data": {
"Status": "SUCCESS",
"Name": "Facebook Inc",
"Symbol": "FB",
"LastPrice": 31.91,
"Change": -1.12,
"ChangePercent": -3.39085679685135,
"Timestamp": "Fri May 25 16:00:05 UTC-04:00 2012",
"MarketCap": 20214729720,
"Volume": 37189630,
"ChangeYTD": 0,
"ChangePercentYTD": 0,
"High": 32.95,
"Low": 31.11,
"Open": 32.9
}
})
I also have the following code that IS working with google api which will be leaving us in October this year.
<?php
//Obtain Quote Info
$quote = file_get_contents('http://finance.google.com/finance/info?client=ig&q=NASDAQ:' . $stock . '');
//Remove CR's from ouput - make it one line
$json = str_replace("\n", "", $quote);
//Remove //, [ and ] to build qualified string
$data = substr($json, 4, strlen($json) -5);
//decode JSON data
$json_output = json_decode(utf8_decode($data));
// get the last price
$perc = $json_output->c;
$last = $json_output->l;
$date = $json_output->lt;
$name = $json_output->t;
?>
For whatever reason I cannot figure out how to get the other to work with my code. Anyone have any suggestions?
Just use http://dev.markitondemand.com/Api/Quote/json?symbol=AAPL as the url, leaving out the p in json.
<?php
$stock = "FB";
//Obtain Quote Info
//$quote = file_get_contents('http://dev.markitondemand.com/Api/Quote/json?symbol='.$stock);
//or with curl
$quote = curl_get('http://dev.markitondemand.com/Api/Quote/json?symbol='.$stock);
function curl_get($url){
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_REFERER, $url);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/1.0");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
//decode JSON data
$json_output = json_decode(utf8_decode($quote));
$perc = $json_output->Data->ChangePercent;
$last = $json_output->Data->LastPrice;
$date = $json_output->Data->Timestamp;
$name = $json_output->Data->Name;
print_r($json_output);
/*
stdClass Object
(
[Data] => stdClass Object
(
[Status] => SUCCESS
[Name] => Facebook Inc
[Symbol] => FB
[LastPrice] => 31.91
[Change] => -1.12
[ChangePercent] => -3.3908567968514
[Timestamp] => Fri May 25 16:00:05 UTC-04:00 2012
[MarketCap] => 20214729720
[Volume] => 37189630
[ChangeYTD] => 0
[ChangePercentYTD] => 0
[High] => 32.95
[Low] => 31.11
[Open] => 32.9
)
)*/
?>
The code you are using for Google Finance is directly customized to work with the output from the Google Finance API you're using.
Here is the output from Google Finance:
// [
{
"id": "296878244325128"
,"t" : "FB"
,"e" : "NASDAQ"
,"l" : "31.91"
,"l_cur" : "31.91"
,"s": "0"
,"ltt":"4:00PM EDT"
,"lt" : "May 25, 4:00PM EDT"
,"c" : "-1.12"
,"cp" : "-3.39"
,"ccol" : "chr"
}
]
The part of your code that does:
$data = substr($json, 4, strlen($json) -5);
is exactly stripping out the unwanted characters from the GF output. For your new output wrapped inside the anonymous function, I suggest the following:
<?php
preg_match('/\(function\(\) \{\}\)\((.*)\)/', $input_string, $matches);
$data_json = $matches[1];
$json_output = json_decode($data_json, true); //true = assoc array
$final_json = $json_output['Data'];
This will assign a valid json string to the $json variable, where $input_string is the input you listed in your question. And $final_json will contain whatever is inside the Data: property of the original json.
Related
i'm trying to retrieve data in real time using the leadgen event
i'm using the Facebook ads SDK for php
i succeeded in seting up an endpoint to ingest the realtime ping
here is my error_log file
(
[entry] => Array
(
[0] => Array
(
[changes] => Array
(
[0] => Array
(
[field] => leadgen
[value] => Array
(
[ad_id] => 0
[form_id] => 1602570684541170
[leadgen_id] => 1629665456004730
[created_time] => 148036545636
[page_id] => 1870793756647618
[adgroup_id] => 0
)
)
)
[id] => 1870793717274654
[time] => 14803464737
)
)
[object] => page
)
i'm trying to retrieve this kind of data
{
"data": [
{
"created_time": "2015-02-28T08:49:14+0000",
"id": "<LEAD_ID>",
"ad_id": "<AD_ID>",
"form_id": "<FORM_ID>",
"field_data": [
{
"name": "car_make",
"values": [
"Honda"
]
},
{
"name": "full_name",
"values": [
"Joe Example"
]
},
{
"name": "email",
"values": [
"joe#example.com"
]
},
]
}
],
"paging": {
"cursors": {
"before": "OTc2Nz3M5MTgyMzU1NDMy",
"after": "OTcxNjcyOTg5ANTI4NzE4"
}
}
}
here is my webhook code
<?php
require_once 'facebook-php-ads-sdk-master/vendor/autoload.php';
use FacebookAds\Object\LeadgenForm;
use FacebookAds\Api;
use FacebookAds\Object\Ad;
use FacebookAds\Object\Lead;
$app_id='148247344564502719';
$app_secret='17489f3e0f8235645413f5dd593e67787';
$access_token='1482473465452719';
// Initialize a new Session and instanciate an Api object
Api::init($app_id, $app_secret, $access_token);
// The Api object is now available trough singleton
$api = Api::instance();
$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token'];
if ($verify_token === 'abc123') {
echo $challenge;
}
$input = json_decode(file_get_contents('php://input'), true);
error_log(print_r($input, true));
$form_id = $input['entry'][0]['changes'][0]['value']['form_id'];
$ad_id = $input['entry'][0]['changes'][0]['value']['ad_id'];
$leadgen_id = $input['entry'][0]['changes'][0]['value']['leadgen_id'];
/*$form = new Lead($leadgen_id);
$form->read();
$ad = new Ad($ad_id);
$leads = $ad->getLeads();*/
$form = new LeadgenForm($form_id);
$leads = $form->getLeads();
error_log(print_r($leads, true));
?>
here is the error :
Fatal error: Uncaught exception 'Exception' with message 'field 'id' is required.' in /www/wibonus/public_html/facebook-php-ads-sdk-master/src/FacebookAds/Object/AbstractCrudObject.php:123 Stack trace: #0 /www/wibonus/public_html/facebook-php-ads-sdk-master/src/FacebookAds/Object/Ad.php(290): FacebookAds\Object\AbstractCrudObject->assureId() #1 /www/wibonus/public_html/webhook.php(38): FacebookAds\Object\Ad->getLeads() #2 {main} thrown in /www/wibonus/public_html/facebook-php-ads-sdk-master/src/FacebookAds/Object/AbstractCrudObject.php on line 123
Instead of using Facebook SDK you can do simple CURL request from your PHP code to retrieve lead form data.
Here is the code.
$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token'];
if ($verify_token === 'abc123') {
echo $challenge;
}
$input = json_decode(file_get_contents('php://input'), true);
error_log(print_r($input, true));
$form_id = $input['entry'][0]['changes'][0]['value']['form_id'];
$ad_id = $input['entry'][0]['changes'][0]['value']['ad_id'];
$leadgen_id = $input['entry'][0]['changes'][0]['value']['leadgen_id'];
$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token'];
if ($verify_token === 'abc123') {
echo $challenge;
}
$input = json_decode(file_get_contents('php://input'), true);
error_log(print_r($input, true));
$form_id = $input['entry'][0]['changes'][0]['value']['form_id'];
$ad_id = $input['entry'][0]['changes'][0]['value']['ad_id'];
$leadgen_id = $input['entry'][0]['changes'][0]['value']['leadgen_id'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com/v2.8/" . $leadGenId . "?access_token={ACCESS_TOKEN}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
$leadData = json_decode($result, true);
$lead = [];
for($i = 0; $i < count($leadData); $i++)
{
$lead[$leadData[$i]['name']] = $leadData[$i]['values'][0];
}
print_r($lead);
You should return $challenge in your callback URL. (Note:If you are working on webhook)
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"
)
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';
Below is my code, I am trying to get particular api response (msg,amt) in php string.
........................................................................................................................................
$key = "XXXXX";
$mykey = "XXXXX";
$command = "Check";
$value = "5454355435";
$r = array('key' => $key , 'value' => $value, 'command' => $command);
$qs= http_build_query($r);
$wsUrl = "https://info.service-provider.com";
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $wsUrl);
curl_setopt($c, CURLOPT_POST, 1);
curl_setopt($c, CURLOPT_POSTFIELDS, $qs);
curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0);
$o = curl_exec($c);
if (curl_errno($c)) {
$sad = curl_error($c);
throw new Exception($sad);
}
curl_close($c);
$valueSerialized = #unserialize($o);
if($o === 'b:0;' || $valueSerialized !== false) {
print_r($valueSerialized);
}
print_r($o);
RESPONSE:
{"status":1,"msg":"1 out of 1 Transactions Fetched Successfully","transaction_details":{"2767712494": {"mihpayid":"268999084","request_id":"","ref_num":"020814301298","amt":"1.00","txnid":"5454355435","additional_charges":"0.00","productinfo":"SHIRT"}}}
Your string is in json format. To get value from it, you should convert it into an array like this:
$json = '{"status":1,"msg":"1 out of 1 Transactions Fetched Successfully","transaction_details":{"2767712494": {"mihpayid":"268999084","request_id":"","ref_num":"020814301298","amt":"1.00","txnid":"5454355435","additional_charges":"0.00","productinfo":"SHIRT"}}}';
$array = json_decode($json, true);
echo '<pre>'; print_r($array);
Your array will look like this:
Array
(
[status] => 1
[msg] => 1 out of 1 Transactions Fetched Successfully
[transaction_details] => Array
(
[2767712494] => Array
(
[mihpayid] => 268999084
[request_id] =>
[ref_num] => 020814301298
[amt] => 1.00
[txnid] => 5454355435
[additional_charges] => 0.00
[productinfo] => SHIRT
)
)
)
To get msg you should write like this:
echo $array['msg'];
You can get more information from json_decode
Let me know for more help.
This response looks like JSON format.
Pass this response string to php method json_decode like:
$response = json_decode($yourResponseString,true);
and then you should be able to access it's properties like a regular associative array:
$msg = $response['msg'];
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
)
)