Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I use some website that give me information about IP but the information that that website return in JSON and I don't know the JSON. I want to use this to check the user if it is from IR do something but I dont know how to use JSON in php,
Here is the JSON that the website return:
{"address":"0.0.0.0.0","country":"IR","stateprov":"somewhere ","city":"Tehr\somewhere (somewhere)"}
I want to save the country in a variable and add this code to my website:
<?php
if($country == 'IR'){
//Do somethong
}
$country is the country name that return from the website,
You'll need to use json_decode().
$s = '{"address":"0.0.0.0.0","country":"IR","stateprov":"somewhere ","city":"Tehrsomewhere (somewhere)"}';
$d = json_decode($s);
Which returns:
stdClass Object
(
[address] => 0.0.0.0.0
[country] => IR
[stateprov] => somewhere
[city] => Tehrsomewhere (somewhere)
)
That would allow you to check the country/other fields like this:
if($d->country == 'IR') {
// do something
}
NOTE: you had an error (invalid json) in your "city" field, the \ makes it invalid.
Example
You can ensure that your json is valid by checking it at JSON Lint.
I think you are looking for the function json_decode.It decodes the JSON string
See the documentation here
You have to first decode this json string.
$data = '{"address":"0.0.0.0.0","country":"IR","stateprov":"somewhere ","city":"Tehr\somewhere (somewhere)"}';
$decodeData = json_decode($data);
Then use this decode json string in php like this.
if($decodeData->country == 'IR'){
//Do somethong
}
First of all i would like to inform you that given json is not valid. "city" : "Tehr\somewhere (somewhere)" is not valid because of "\".
So change it into below given format.
$jsonEncode = { "address": "0.0.0.0.0","country": "IR","stateprov": "somewhere ","city": "There somewhere (somewhere)"}
$jsonDecode = json_decode($jsonEncode,true);
Now you will get the value in array format.
Array(
[address] => 0.0.0.0.0
[country] => IR
[stateprov] => somewhere
[city] => There somewhere (somewhere)
);
print_r($jsonDecode['city']); will give you city name or details
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
The website http://tracker.ets2map.com/v2/fullmap contains the data I wish to retrieve every 10 seconds using the following code:
<?php
$content = file_get_contents("http://tracker.ets2map.com/v2/fullmap");
$result = json_decode($content);
print_r($result);
I wish to get the info in the form
[{"name":"\u0420\u041e\u0421\u0421\u0418\u042f","x":-11409,"y":11749,"id":73469},{"name":"NikJZX","x":-12305,"y":-6239,"id":401390},{"name":"Efremov777","x":-12390,"y":-5636,"id":1755318}, ...]
But using the code above the data is all scrambled
Thanks for any help.
Edit:
I realise now that scramble is very misleading.
I have fixes my original problem, but now the data returns with a / in it.
Eg.
"{\"Trucks\": {\"1743637\": {\"name\": \"benanayan2\", \"h\": 0.55, \"p_id\": \"2043\", \"server\": 2, \"mp_id\": 1743637, \"t\": 1511366599, \"online\": true, \"y\": -27679, \"x\": 7203}, \"1229525\": {\"name\": \"BoeinGTranSErtu\u011frul15\", \"h\": 2.81, \"p_id\": \"868\", \"server\": 2, \"mp_id\": 1229525, \"t\": 1511366599, \"online\": true, \"y\": -9884, \"x\": -8956}, \"1717847\": {\"name\": \"[VNS] PH\u1ea0M \u0110I\u1ec6P\", \"h\": 2.2, \"p_id\": \"176\", \"server
<?php
$content = file_get_contents("http://tracker.ets2map.com/v2/fullmap");
$result = json_decode($content,true);
echo '<pre>';
print_r($result);
I think you mean that your print_r messes the data in printing. Try my code to get the data print clear and readable. And also when you decode to array , use true , otherwise you end up with an std class object not easily parsed.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I wanted this type of json using php and mysql. I tried a lot but the json which I get are duplicate data and very complex.
JSON I need:
{"data":[
{"Maharashtra":[
{"Mumbai":[
{"place_name":"Gateway of India"},
{"place_name":"Marine Lines"},
{"place_name":"Juhu"}
]},
{"Pune":[
{"place_name":"Singhad"},
]}
}],
{"Goa":[
{"Panji":[
{"place_name":"panji"}
]}
]}
}]}
PHP code:
<?php
require('database.php');
$counter=0;
$state = "SELECT distinct(s.state_name)
, ac.city_name
FROM all_state s, all_city ac
WHERE s.s_id = ac.state_id;";
$resultState = $conn->query($state);
$return_arr['data'] = array();
while($row = $resultState->fetch_assoc()){
$getStateName = $row['state_name'];
$getCityName = $row['city_name'];
$state_array[$getStateName] = array($getCityName);
array_push($return_arr['data'], $state_array);
}
echo json_encode($return_arr);
your query only returns states and cities so data like:
{"place_name":"Gateway of India"},
{"place_name":"Marine Lines"},
{"place_name":"Juhu"}
is not there: to push the data you are getting in to propper array use this:
while($row = $resultState->fetch_assoc()){
$stateArray[$row['state']][$row['city']] = array(); // the empty array is there to push your remaining data in to
}
$result = array('data' => $stateArray);
echo json_encode($result);
UPDATE TO ANSWER COMMENT:
You can add details to your array like this (or any other way, there are many, this is the most basic):
$stateArray[$stateYouWant][$cityYouWant]['place_names'] = array('Gateway of India', 'Marine Lines', 'Juhu');
This will give ytou something like:
{"Maharashtra":[
{"Mumbai":[
{"place_names":[
"Gateway of India",
"Marine Lines",
"Juhu"]}
]},
The variation you want:
{"Mumbai":[
{"place_name":"Gateway of India"},
{"place_name":"Marine Lines"},
{"place_name":"Juhu"}
]},
Is not possible because json is actually a string representation of associative array (or JS object) and that means you can not have same name keys on the same array level.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
i have little problem with inserting data to my database.
I get this error but i have no idea way. I have almost identical query on other script and it works fine but this one does not. I check the POST data on chrome inspector it shows fine.
if you have idea whats wrong with it, let me know.
Thanks in Advance.
$fact_total = (float)$_POST['precio'];
$fact_btax = (float)$_POST['precio_sin'];
$fact_tax = (float)$_POST['impuestos'];
$fact_name = e($_POST['fact_name']);
$fact_tipo = e($_POST['fact_serv']);
$fact_tax_rate = 21;
try{
$handler = $db->prepare('INSERT INTO fact_info
(id_client, cl_name, cl_last_name, cl_last_name_2, cl_email, cl_tel, cl_doc_type, cl_doc, cl_via, cl_street, cl_number, cl_level, cl_stairs, cl_door, cl_provincia, cl_city, cl_cod_postal, fact_urgencia, fact_name, fact_tipo, fact_total, fact_btax, fact_tax, fact_tax_rate, created ) VALUES (:id_client, :cl_name, :cl_last_name, :cl_last_name_2, :cl_email, :cl_tel, :cl_doc_type, :cl_doc, :cl_via, :cl_street, :cl_number, :cl_level, :cl_stairs, :cl_door, :cl_provincia, :cl_city, :cl_cod_postal, :fact_urgencia, :fact_name, :fact_tipo, :fact_total, :fact_btax, :fact_tax, :pres_tax_rate, NOW())');
$handler->execute(array(
':id_client' => $client_ids,
':cl_name' => e($_POST['fact_cl_name']),
':cl_last_name' => e($_POST['fact_lastname']),
':cl_last_name_2' => e($_POST['fact_lastname_2']),
':cl_email' => e($_POST['fact_email']),
':cl_tel' => e($_POST['fact_tel']),
':cl_doc_type' => e($_POST['fact_document_type']),
':cl_doc' => e($_POST['fact_document_number']),
':cl_via' => e($_POST['fact_dir_via']),
':cl_street' => e($_POST['fact_dir_calle']),
':cl_number' => (int)$_POST['fact_dir_number'],
':cl_level' => e($_POST['fact_dir_level']),
':cl_stairs' => e($_POST['fact_dir_stairs']),
':cl_door' => e($_POST['fact_dir_door']),
':cl_provincia' => e($_POST['fact_dir_provincia']),
':cl_city' => e($_POST['fact_dir_localidad']),
':cl_cod_postal' => (int)$_POST['fact_dir_cod_postal'],
':fact_urgencia' => '1',
':fact_name' => $fact_name,
':fact_tipo' => $fact_tipo,
':fact_total' => $fact_total,
':fact_btax' => $fact_btax,
':fact_tax' => $fact_tax,
':fact_tax_rate' => $fact_tax_rate
));
$fact_id = $db->lastInsertId();
foreach ($_POST['inv_desc'] as $key => $value) {
$handler4 = $db->prepare('INSERT INTO fact_content (id_fact, fact_desc, fact_qty, fact_price, fact_subtotal) VALUES (:id_fact, :fact_desc, :fact_qty, :fact_price, :fact_subtotal)');
$handler4->execute(array(
':id_fact' => $fact_id,
':fact_desc' => e($_POST['inv_desc'][$key]),
':fact_qty' => (float)$_POST['inv_qty'][$key],
':fact_price' => (float)$_POST['inv_precio'][$key],
':fact_subtotal' => (float)$_POST['inv_subtotal'][$key]
));
}
header('Location: fact_confirm.php?fact_id='.$fact_id.'');
exit();
I'll explain you why this error occurs.
SQLSTATE[HY093]: Invalid parameter number
This error basically occurs because of the following reasons.
Reason1
As the error name suggests, there is some difference between the number of parameters in your prepared query. What I mean is, take a look at the following example:
$s = $conn->prepare("INSERT INTO table(column1,column2) values(:column1)
$s->bindParam(':column1', $column1Value);
$s->bindParam(':column2', $column2Value);
Now, this will generate the error you mentioned because you're trying to insert into 2 columns, but are only providing value for 1.
Reason2
$s = $conn->prepare("INSERT INTO table(column1) values(:column1,:column2)
$s->bindParam(':column1', $column1Value);
$s->bindParam(':column2', $column2Value);
Now this would generate an error because you're trying to insert value into one column, but providing 2 values inside the VALUE section of the query.
Reason3
$s = $conn->prepare("INSERT INTO table(column1,column2) values(:column1,:column2)
$s->bindParam(':column1', $column1Value);
In this case, you've written the query part correct. However, you missed binding the parameters for the second value, the :column2.
These are the reasons why this error bumps up. Check your code and you'd find out what error out of these 3 you've made.
It appears that there is no :fact_tax_rate. Looks like a typo. Your last insert statement column inserts :pres_tax_rate.
Your first insert has the wrong variable name for the second to last value. Change :pres_tax_rate to :fact_tax_rate
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I declared one variables like this
echo $OPTIONS="500=>250.00, 1000=>500.00,2500=>1100.00,5000=>2250.00";
and
I got this variables through file_get_contents() functions.
$contents = file_get_contents(SERVICE_URL."options_config.php?options=".$OPTIONS);
$package=array($contents)
foreach($package as $pack=>$price)
{
echo $pack;
}
But I got 0 values. What is the problem?
print_r($package);
The result is :
Array ( [0] => 500=>250.00, 1000=>500.00,2500=>1100.00,5000=>2250.00 )
I want the result like this
500 as 250.00
1000 as 500.00
I think what you are looking for is serialize and unserialize
Example: test.php
<?php
// Handle Get Request
// This portion of your code can be on another file
//
if (isset($_GET['getOptions']))
{
$myOptions = array(
500 => 250.00,
1000 => 500.00,
2500 => 1100.00,
5000 => 2250.00
);
exit(serialize($myOptions));
}
// Sample Usage
$options = file_get_contents('http://localhost/test.php?getOptions');
$options = unserialize($options);
// Debug
var_dump($options);
?>
Outputs:
I have a problem with json parsing.
I have already read the many questions here on stackoverflow but I can't figured out what I'm missing.
In my site I use Facebook Api to post my feed using curl and it respond with a json message.
I take this response and I save it in my database.
In my Backoffice I need to retrieve this message and print it in case of error.
Here an example about an error message:
{"error":{"message":"(#1500) The url you supplied is invalid","type":"OAuthException","code":1500}}
In my php page I need to get just the message part so I did:
$message = get from the db and fetch;
$error_array = json_decode($message,true);
print_r($error_array);
but it doesn't print anything, just a blank page.
If I just print $message I can see the entire string.
What am I missing?
This issue it's driving me crazy all day long!!
I tried the following:
<pre>
<?php
$jsonStr = '{"error":{"message":"(#1500) The url you supplied is invalid","type":"OAuthException","code":1500}}';
$error_array = json_decode($jsonStr, true);
print_r($error_array);
?>
and getting output:
Array
(
[error] => Array
(
[message] => (#1500) The url you supplied is invalid
[type] => OAuthException
[code] => 1500
)
)
It's working as intended.
I suspect the problem is with this:
$message = get from the db and fetch;
After you load the $message variable, do a var_dump($message) and see if the string is in there (as expected).
$jsonString = '["m#gmail.com","b#gmail.com","c#gmail.com"]';
$arrayOfEmails=json_decode($jsonString);
Or
$jsonString = "[\"a#gmail.com\",\"b#gmail.com\",\"c#gmail.com\"]";
$arrayOfEmails=json_decode($jsonString);