I can get data from a website with CURL.
I want to convert this data to json.
my code:
<?php
function Curlconnect($start,$end,$website) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $website);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$website = curl_exec($ch);
preg_match_all('#'.$start.'(.*?)'.$end.'#si',$website,$ver);
return $ver[1];
curl_close($ch);
}
function nt($start,$bit,$data,$a) {
preg_match_all('#'.$start.'(.*?)'.$bit.'#si',$data,$ver);
return $ver[1];
}
$url = 'http://www.url.com';
$getdata = Curlconnect('<h4','h4>',$url);
for ($a=0; $a<count($getdata); $a++) {
$printdata = nt('>','</',$getdata[$a],$a);
echo $printdata[0]. '<br />';
}
?>
Output:
1
27
32
66
94
I want to convert this data to json like that:
{
"data":{
"numbers":
[
"1",
"27",
"32",
"66",
"94",
]
}
}
How Can I do that?
Thank you very much.
Please try this
$url = 'http://www.url.com';
$getdata = Curlconnect('<h4','h4>',$url);
$jsonData = ["data"];
$jsonData["numbers"] = [];
for ($a=0; $a<count($getdata); $a++) {
$printdata = nt('>','</',$getdata[$a],$a);
$jsonData["numbers"][] = $printdata[0];
}
echo json_encode($jsonData);
Related
I am using curl_multi to send 2 post requests, the data is coming back as one $response correctly, I need to know the correct way to now handle this JSON data in PHP.
When I echo between <pre> tags my JSON is displayed correctly, however now I'm not sure how to take the data I want from it with PHP.
This is usually an easy task with a single API but I'm not sure why I'm having so much trouble with this here whilst using curl_multi!
json being returned inside my pre tags;
{
"Vehicles": [
{
"ExternalVehicleId": "9uq0jz1c",
"StockId": "1234",
"Errors": []
}
]
}
{
"Finance": [
{
"ExternalVehicleId": "9uq0jz1d",
"StockId": "4321",
"Errors": []
}
]
}
This is how the json comes back, but there are way more nested arrays. All appear to be in correct syntax wise.
And here's my php which I'm pretty sure is all fine;
$mh = curl_multi_init();
foreach ($urls as $key => $url) {
$chs[$key] = curl_init($url);
curl_setopt($chs[$key], CURLOPT_RETURNTRANSFER, true);
curl_setopt($chs[$key], CURLOPT_HEADER, false);
curl_setopt($chs[$key], CURLOPT_CONNECTTIMEOUT, 200);
curl_setopt($chs[$key], CURLOPT_TIMEOUT_MS, 25000);
curl_setopt($chs[$key], CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($chs[$key], CURLOPT_POST, true);
curl_setopt($chs[$key], CURLOPT_POSTFIELDS, json_encode($request_contents[$key]));
curl_setopt($chs[$key], CURLOPT_HTTPHEADER, $headers);
curl_multi_add_handle($mh, $chs[$key]);
}
$running = null;
do {
curl_multi_exec($mh, $running);
} while ($running);
foreach (array_keys($chs) as $key) {
$error = curl_error($chs[$key]);
$last_effective_URL = curl_getinfo($chs[$key], CURLINFO_EFFECTIVE_URL);
$time = curl_getinfo($chs[$key], CURLINFO_TOTAL_TIME);
$response = curl_multi_getcontent($chs[$key]); // get results
if (!empty($error)) {
echo "The request $key return a error: $error" . "\n";
} else {
echo "The request to '$last_effective_URL' returned '$response' in $time seconds." . "\n";
echo "<pre>";
echo $response;
echo "</pre>";
}
curl_multi_remove_handle($mh, $chs[$key]);
}
curl_multi_close($mh);
Join the responses into a single JSON array, which you can then json_decode():
$responses = [];
foreach (array_keys($chs) as $key) {
$responses[] = curl_multi_getcontent($chs[$key]);
}
$json = json_decode( '[' . join(',', $responses) . ']' );
var_dump($json);
You could unpack the response object with a foreach.
Something like
foreach($response as $value->$index){
echo “value ” . $value . “ index: ” . $index;
}
This is an example and should give you an idea how to debug your code.
I’m typing from a phone so I’m sorry
You may need to put a comma after closing the Vehicles brackets
{
"Vehicles": [
{
"ExternalVehicleId": "9uq0jz1c",
"StockId": "1234",
"Errors": []
}
]
}
,
{
"Finance": [
{
"ExternalVehicleId": "9uq0jz1d",
"StockId": "4321",
"Errors": []
}
]
}
I have below code & I am generating tracking_id values manually & its working fine :
<?php
$data = [
"client_reference_id" => "ABCD",
"tracking_id" => "1234",
];
$data = json_encode($data);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$curl_response = curl_exec($curl);
curl_close($curl);
echo $curl_response ."\n";
Result :
{"response":[{"tracking_id":"1234",}],
Now i need to create tracking_id dynamically.... so i tried like below :
"tracking_id" => "$r = 'DOCC'. mt_rand(0000000001,9999999999); echo $r;",
I got below Result :
{"response":[{"tracking_id":" = 'DOCC'. mt_rand(0000000001,9999999999); echo ;","
But i should get some random number as tracking_id....
Means php code inside parameter is not working....
As your require 10 digit random number:
function randomNumber($length) {
$result = '';
for($i = 0; $i < $length; $i++) {
$result .= mt_rand(1, 9);
}
return $result;
}
$data = [
"client_reference_id" => "ABCD",
"tracking_id" => 'DOCC'.randomNumber(10);//no need to echo, just assign it
];
$data = json_encode($data);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$curl_response = curl_exec($curl);
curl_close($curl);
echo $curl_response ."\n";
Refactor your code:
$r = 'DOCC'. mt_rand(0000000001,9999999999);
$data = [
"client_reference_id" => "ABCD",
"tracking_id" => $r,
];
Just replace $data array with the following.
$data = [
"client_reference_id" => "ABCD",
"tracking_id" => 'DOCC'. mt_rand(0000000001,9999999999),
];
I've been trying to run CURL in a foreach loop to extract information from the cryptocompare.com API. As soon as I call the following function, my code just stops working. There is no output.
$fullArray[$symbol]['Price'] = getThePrice($fullArray[$symbol]['Symbol']);
What am I doing wrong? I pasted the code below
include 'helper.php';
$fullArray = array();
//Get List of All Coins and store symbol and ID
$url = "https://min-api.cryptocompare.com/data/all/coinlist";
$jsonArray = getConnection($url);
foreach($jsonArray['Data'] as $value)
{
$symbol = $value['Symbol'];
$fullArray[$symbol]['Symbol'] = $value['Symbol'];
$fullArray[$symbol]['Id'] = $value['Id'];
//call getThePrice function to get Price of ticker
$fullArray[$symbol]['Price'] = getThePrice($fullArray[$symbol]['Symbol']);
}
function getThePrice($input)
{
//Get current price of each coin and store in full array
$url = "https://www.cryptocompare.com/api/data/coinsnapshot/?fsym=".$input."&tsym=USD";
$jsonNewArray = getConnection($url);
if(array_key_exists('PRICE',$jsonNewArray['Data']['AggregatedData']))
{
$returnVariable = $jsonNewArray['Data']['AggregatedData']['PRICE'];
echo "The price of : ".$input." is ".$returnVariable;
}
else{
$returnVariable = "NA";
echo "This price is not available";
}
return $returnVariable;
}
The code in helper.php:
function getConnection($inputHelp)
{
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$inputHelp);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 4);
$json = curl_exec($ch);
if(!$json) {
echo curl_error($ch);
}
curl_close($ch);
$jsonArray = json_decode($json, true);
return $jsonArray;
}
Appreciate any help. Thanks in advance.
I am writing my telegram bot codes in PHP. I would like to split my inline keyboard into 2 or 3 columns. Here is my code:
foreach ($categories as $cat) {
$key[] = array(
array('text'=>$cat['name'],'callback_data'=>'sub-'.$cat['id'])
);
if ($k % 2 == 0) {
$keyoptions[] = $key;
$key = array();
}
$k++;
}
$telegram->SendMessage($userid, $keyoptions);
but my code doesn't work. Where is the problem and how can I solve my issue?
EDIT :
i just used this code
$keyoptions = array_chunk($keyoptions,3);
but still can't find the problem;
Telegram API: inline_keyboard: Array of Array of InlineKeyboardButton
Example:
keyboard: [
["uno :+1:"],["uno \ud83d\udc4d", "due"],["uno", "due","tre"]
]
I don't know what library you are using and what are those fields in your code, but this a working with native telegram API:
function inlineKeyboard($text, $chatID, $btnNames, $callBackDatas)
{
$inlineRow = array(); // this is array for each row of buttons
$i = 0;
foreach ($btnNames as $name) {
array_push($inlineRow, array("text" => $name, "callback_data" => $callBackDatas[$i]));
$i++;
}
/* if you need multiple rows then just create other inlineRow arrays
and push to this array below */
$inlineKeyboard = array($inlineRow);
$keyboard = array(
"inline_keyboard" => $inlineKeyboard
);
$postfields = array
(
'chat_id' => "$chatID",
'text' => $text,
'reply_markup' => json_encode($keyboard)
);
send('sendMessage', $postfields);
}
define('BaseURL', 'https://api.telegram.org/bot<TOKEN>');
function send($method, $datas)
{
$url = BaseURL . "/" . $method;
if (!$curld = curl_init()) {
exit;
}
curl_setopt($curld, CURLOPT_POST, true);
curl_setopt($curld, CURLOPT_POSTFIELDS, $datas);
curl_setopt($curld, CURLOPT_URL, $url);
curl_setopt($curld, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($curld);
curl_close($curld);
return $output;
}
i just want get the data from the json link with the id == 0
how i can make this !?
<?php
$claw = "https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/43216818/ranked?season=SEASON4&api_key=010ba2bc-2c40-4b98-873e-b1d148c9e379";
$z0r = file_get_contents($claw);
$gaza = json_decode($z0r, true);
foreach ($gaza['champions'] as $key => $value) {
if ($value['id'] == 0) {
$wins = $value['totalTripleKills'];
}
}
?>
my code doesn't show anything ..
can anyone help !?
Your not outputing anything, your just assigning $wins over and over, there could also be an issue with file_get_contents not working as expected with over https urls.
Its faster and easyier to use cURL, also after a quick test it seems,
$value['totalTripleKills'] should be $value['stats']['totalTripleKills']
<?php
$url = "https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/43216818/ranked?season=SEASON4&api_key=010ba2bc-2c40-4b98-873e-b1d148c9e379";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curl);
curl_close($curl);
if(empty($result)) {
echo 'Error fetching: '.htmlentities($url).' '.curl_error($curl);
}else{
$gaza = json_decode($result, true);
foreach ($gaza['champions'] as $key => $value) {
if ($value['id'] == 0) {
echo $value['stats']['totalTripleKills'].'<br>';
}
}
}
Also its a rather large response so you will want to look into caching the result for a while, but thats beyond the questions scope.
There is an error you forgot to enter first in the stats array, otherwise you cannot take totalTripleKills value, then output it.
$claw = "https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/43216818/ranked?season=SEASON4&api_key=010ba2bc-2c40-4b98-873e-b1d148c9e379";
$z0r = file_get_contents($claw);
$gaza = json_decode($z0r, true);
foreach ($gaza['champions'] as $key => $value) {
if ($value['id'] == 0) {
$wins = $value['stats']['totalTripleKills'];
}
}
echo $wins;
Before you parse a json a helpful method to understand json structure of your data is this website: http://jsonlint.com/.
your not outputting anything,
<?php
$claw = "https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/43216818/ranked?season=SEASON4&api_key=010ba2bc-2c40-4b98-873e-b1d148c9e379";
$z0r = file_get_contents($claw);
$gaza = json_decode($z0r, true);
foreach ($gaza['champions'] as $key => $value) {
if ($value['id'] == 0) {
$wins = $value['totalTripleKills'];
}
}
?>
try this
<?php
$claw = "https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/43216818/ranked?season=SEASON4&api_key=010ba2bc-2c40-4b98-873e-b1d148c9e379";
$z0r = file_get_contents($claw);
$gaza = json_decode($z0r, true);
echo "<pre>";
foreach ($gaza['champions'] as $key => $value) {
if ($value['id'] == 0) {
$wins = $value['totalTripleKills'];
var_export( $wins );
}
}
?>