i want to pass array in url, so i have encoded using http_build_query
$filterArray = array('OrderNo'=>$_REQUEST['txtorderno'],
'StoreName'=>$_REQUEST['txtstorename'],
'PartyCode'=>$_REQUEST['txtpartycode'],
'fromdate'=>$_REQUEST['txtfromdate'],
'todate'=>$_REQUEST['txttodate'],
'minamount'=>$_REQUEST['txtminamount'],
'maxamount'=>$_REQUEST['txtmaxamount']);
$data = array('DistributorId' => $_GET['DistributorId'], 'StoreId' => $_GET['StoreId'],'filterArray' => http_build_query($filterArray));
finally my URL is generated like this
http://localhost/test/orderdetails.php?DistributorId=&StoreId=&filterArray=OrderNo%3D1%26StoreName%3D2%26PartyCode%3D3%26fromdate%3D04%252F26%252F2017%26todate%3D04%252F27%252F2017%26minamount%3D111%26maxamount%3D222
now how do i get all the parameters from url ??
i tried to print filterArray parameter like
echo "<pre>";
$arr = (urldecode($_GET['filterArray']));
var_dump($arr);
it prints
string(99) "OrderNo=1&StoreName=2&PartyCode=3&fromdate=04/26/2017&todate=04/27/2017&minamount=111&maxamount=222"
You can use parse_str[1]:
<?php
$inputStr = 'OrderNo=1&StoreName=2&PartyCode=3&fromdate=04/26/2017&todate=04/27/2017&minamount=111&maxamount=222';
parse_str($inputStr, $output);
var_dump($output);
?>
Example: https://3v4l.org/toiKf
[1]: http://php.net/manual/de/function.parse-str.php
Related
I have url like this :
/leads/set_attributes.html?lead_id=3793&name=TEST
I need remove 'name' and return url.
I try do it like this:
$vars = [];
parse_str(html_entity_decode($sAddQuery), $vars);
unset($vars['name']);
$sAddQuery = http_build_query($vars);
But i always get
%3Flead_id=3793
as result. I tried use html_entity_decode for array elements but it did not help. How can i solve this? Thanks
Modify your code to :
<?php
$url = parse_url('/leads/set_attributes.html?lead_id=3793&name=TEST');
$str = $url['query'];
parse_str($str, $params); //parse URL
unset($params['name']); //unset name parameter
$string = http_build_query($params); //again built the URL string
var_dump($string);
?>
Hope it works!
How can I read a JSON data response using php?
This is Code :
$response = Unirest\Request::get("https://montanaflynn-spellcheck.p.mashape.com/check/?text=This+sentnce+has+some+probblems.",
array(
"X-Mashape-Key" => "MY X-Mashape-Key",
"Accept" => "application/json"
)
);
and give me this json data :
{
"original": "This sentnce has some probblems.",
"suggestion": "This sentence has some problems.",
and ...
}
I want to return "suggestion" in a url with $
this is an example :
$user_id = '123456789'
$mytext = '?' // I WANT RETURN "suggestion" HERE !
$url = 'https://api.telegram.org/mytoken/sendMessage?chat_id='.$user_id.'&text='.$mytext
file_get_contents($url);
You can use json_decode().
See:
http://php.net/manual/en/function.json-decode.php
You just need to do:
$response = json_decode($response,1);
echo $response['suggestion'];
Setting the second parameter of json_decode() to 1 (true) will return an associative array of the JSON data.
If you want to include it in a URL using your code example:
$user_id = '123456789'
$json = json_decode($response,1);
$mytext = $json['suggestion'];
$url = 'https://api.telegram.org/mytoken/sendMessage?chat_id='.$user_id.'&text='.$mytext
file_get_contents($url);
Use json_decode to convert json_response to array.Add second parameter of 'true' to make it an array that you should be familiar with.
Access suggestion variable by specifying it.
$response = Unirest\Request::get("https://montanaflynn-spellcheck.p.mashape.com/check/?text=This+sentnce+has+some+probblems.",
array(
"X-Mashape-Key" => "MY X-Mashape-Key",
"Accept" => "application/json"
)
);
$data=json_decode($response,true);
$url = 'https://api.telegram.org/mytoken/sendMessage?chat_id='.$user_id.'&text='.$data['suggestion'];
echo $url;
I have probably spent all day trying to figure this out. I have read multiple questions here on stack and also have been reading articles and checking on documentation, but I can't seem to figure out why this batch of code just produces a null output. Am I missing brackets, calling something wrong, ect?
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str);
$temp = $json['main']['temp_min'];
$content = $temp;
$array = array(
"content" => $content,
refresh_requency => 30
);
echo json_encode($array);
?>
Again what I'm asking is can someone point out to me or tell me what I'm doing wrong. Is it my server that's just not handling the data correctly? That could be a possibility.
One other thing I've tried is to just print out $temp and/or the other variable like $str. When I do that though they don't even show up so that's what I think my problem is just not sure how to fix it.
Update
I've come to the conclusion that it's my web hosting service. As if I add var_dump($json) I get a null output null output.
Also to confirm that its my webhost if I run error_reporting(E_ALL); ini_set('display_errors', 1); it points to the file php.ini not allowing outgoing connections. I edited that same file on my local home server(raspberry pi) ran the same file and it works fine.
Below is the working solution for your above code:
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str, true);
$temp = $json['main']['temp_min'];
$content = $temp;
$array = array(
"content" => $content,
"refresh_requency" => 30
);
echo json_encode($array);
?>
When I executed your code, I found 2 problem into your code snippet:
1) You were trying to use object of type stdClass as array.
Solution:
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str);
$temp = $json->main->temp_min;
$content = $temp;
$array = array(
"content" => $content,
"refresh_requency" => 30
);
echo json_encode($array);
?>
2) You did not put array key into quotes:
$array = array(
"content" => $content,
refresh_requency => 30
);
It should be :
$array = array(
"content" => $content,
"refresh_requency" => 30
);
Access $temp like this
$temp = $json->main->temp_min;
you will get the desired output.
Also, you need to allow allow_url_fopen in your php.ini config file. Some hosts disallow it for security reasons
$json = json_decode($str, true);
You need second argument to convert json string into associative array instead of the object. And you are trying to use array ($json['main']['temp_min']), not object. Also
$array = array(
"content" => $content,
"refresh_requency" => 30
);
The code looks like
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str, true);
$content = $json['main']['temp_min'];
$array = array(
"content" => $content,
"refresh_requency" => 30
);
echo json_encode($array);
And result is http://codepad.viper-7.com/euBNAk :
{"content":44.6,"refresh_requency":30}
The second parameter of json_decode() is assoc (associative). By default it is 0. When it is 0 (default) the json_decode() will return an object, not an array. That's why you are unable to access temp_min by using $json['main']['temp_min'];
However If you use with the value 1 as second parameter, the function will return an array. Parameter 1 means setting associative to 1 (true). So use $json = json_decode($str, true); instead of $json = json_decode($str);. You will be able to access with $json['main']['temp_min']; now.
Also you forgot double quote on line 13 (refresh_requency). Goodluck.
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str, true);
$temp = $json['main']['temp_min'];
$content = $temp;
$array = array(
"content" => $content,
"refresh_requency" => 30
);
echo json_encode($array);
Just want help
I change your code like this and that be correctly
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str, TRUE); // Wrong here
$temp = $json['main']['temp_min'];
$content = $temp;
$array = array(
"content" => $content,
"refresh_requency" => 30 // And wrong here, it's must string
);
echo json_encode($array);
?>
More information about json decode in php to array or object http://php.net/manual/en/function.json-decode.php
Here is the url:
http://localhost/test.php?id=http://google.com/?var=234&key=234
And I can't get the full $_GET['id'] or $_REQUEST['d'].
<?php
print_r($_REQUEST['id']);
//And this is the output http://google.com/?var=234
//the **&key=234** ain't show
?>
$get_url = "http://google.com/?var=234&key=234";
$my_url = "http://localhost/test.php?id=" . urlencode($get_url);
$my_url outputs:
http://localhost/test.php?id=http%3A%2F%2Fgoogle.com%2F%3Fvar%3D234%26key%3D234
So now you can get this value using $_GET['id'] or $_REQUEST['id'] (decoded).
echo urldecode($_GET["id"]);
Output
http://google.com/?var=234&key=234
To get every GET parameter:
foreach ($_GET as $key=>$value) {
echo "$key = " . urldecode($value) . "<br />\n";
}
$key is GET key and $value is GET value for $key.
Or you can use alternative solution to get array of GET params
$get_parameters = array();
if (isset($_SERVER['QUERY_STRING'])) {
$pairs = explode('&', $_SERVER['QUERY_STRING']);
foreach($pairs as $pair) {
$part = explode('=', $pair);
$get_parameters[$part[0]] = sizeof($part)>1 ? urldecode($part[1]) : "";
}
}
$get_parameters is same as url decoded $_GET.
While creating url encode them with urlencode
$val=urlencode('http://google.com/?var=234&key=234')
Click here
and while fetching decode it wiht urldecode
You may have to use urlencode on the string 'http://google.com/?var=234&key=234'
I had a similar problem and ended up using parse_url and parse_str, which as long as the URL in the parameter is correctly url encoded (which it definitely should) allows you to access both all the parameters of the actual URL, as well as the parameters of the encoded URL in the query parameter, like so:
$get_url = "http://google.com/?var=234&key=234";
$my_url = "http://localhost/test.php?id=" . urlencode($get_url);
function so_5645412_url_params($url) {
$url_comps = parse_url($url);
$query = $url_comps['query'];
$args = array();
parse_str($query, $args);
return $args;
}
$my_url_args = so_5645412_url_params($my_url); // Array ( [id] => http://google.com/?var=234&key=234 )
$get_url_args = so_5645412_url_params($my_url_args['id']); // Array ( [var] => 234, [key] => 234 )
you use bad character like ? and & and etc ...
edit it to new code
see this links
http://antoine.goutenoir.com/blog/2010/10/11/php-slugify-a-string/
http://sourcecookbook.com/en/recipes/8/function-to-slugify-strings-in-php
also you can use urlencode
$val=urlencode('http://google.com/?var=234&key=234')
The correct php way is to use parse_url()
http://php.net/manual/en/function.parse-url.php
(from php manual)
This function parses a URL and returns an associative array containing any of the various components of the URL that are present.
This function is not meant to validate the given URL, it only breaks it up into the above listed parts. Partial URLs are also accepted, parse_url() tries its best to parse them correctly.
if (isset($_SERVER['HTTPS'])){
echo "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]$_SERVER[QUERY_STRING]";
}else{
echo "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]$_SERVER[QUERY_STRING]";
}
CREATE TABLE Posts
{
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(200),
url VARCHAR(200)
}
json.php code
<?php
$sql=mysql_query("select * from Posts limit 20");
echo '{"posts": [';
while($row=mysql_fetch_array($sql))
{
$title=$row['title'];
$url=$row['url'];
echo '
{
"title":"'.$title.'",
"url":"'.$url.'"
},';
}
echo ']}';
?>
I have to generate results.json file.
To generate JSON in PHP, you need only one function, json_encode().
When working with database, you need to get all the rows into array first. Here is a sample code for mysqli
$sql="select * from Posts limit 20";
$result = $db->query($sql);
$posts = $result->fetch_all(MYSQLI_ASSOC);
then you can either use this array directly or make it part of another array:
echo json_encode($posts);
// or
$response = json_encode([
'posts' => $posts,
]);
if you need to save it in a file then just use file_put_contents()
file_put_contents('myfile.json', json_encode($posts));
Use this:
$json_data = json_encode($posts);
file_put_contents('myfile.json', $json_data);
You can create the myfile.json before you run the script.But its not compulsory if you have full sudo privileges(read/write permissions(For of you on Mac).
Here is a working Example:
<?php
// data stored in an array called posts
$posts = Array (
"0" => Array (
"id" => "01",
"title" => "Hello",
),
"1" => Array (
"id" => "02",
"title" => "Yoyo",
),
"2" => Array (
"id" => "03",
"title" => "I like Apples",
)
);
// encode array to json
$json = json_encode($posts);
$bytes = file_put_contents("myfile.json", $json); //generate json file
echo "Here is the myfile data $bytes.";
?>
Insert your fetched values into an array instead of echoing.
Use file_put_contents() and insert json_encode($rows) into that file, if $rows is your data.
If you're pulling dynamic records it's better to have 1 php file that creates a json representation and not create a file each time.
my_json.php
$array = array(
'title' => $title,
'url' => $url
);
echo json_encode($array);
Then in your script set the path to the file my_json.php
Here i have mentioned the simple syntex for create json file and print the array value inside the json file in pretty manner.
$array = array('name' => $name,'id' => $id,'url' => $url);
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($array, JSON_PRETTY_PRINT)); // here it will print the array pretty
fclose($fp);
Hope it will works for you....
You can simply use json_encode function of php and save file with file handling functions such as fopen and fwrite.
First, you need to decode it :
$jsonString = file_get_contents('jsonFile.json');
$data = json_decode($jsonString, true);
Then change the data :
$data[0]['activity_name'] = "TENNIS";
// or if you want to change all entries with activity_code "1"
foreach ($data as $key => $entry) {
if ($entry['activity_code'] == '1') {
$data[$key]['activity_name'] = "TENNIS";
}
}
Then re-encode it and save it back in the file:
$newJsonString = json_encode($data);
file_put_contents('jsonFile.json', $newJsonString);
copy
Use PHP's json methods to create the json then write it to a file with fwrite.