get value from json file via php non array - php

I'm a beginner in json please help
I'm trying to access value of certain objects from an online published json file via php script and not able to do so following the examples from this forum
<?php
$str = file_get_contents('http://data.companieshouse.gov.uk/doc/company/02050399.json');
$json = json_decode($str, true);
$companyname = $json["primary topic"]["CompanyName"];
print $companyname;
?>
i get the following error
( ! ) Notice: Undefined index: primary topic in C:\wamp\www\json.php on line 4
Call Stack
# Time Memory Function Location
1 0.0000 244456 {main}( ) ..\json.php:0
I have tried single and double quotes, [0] for array but to no avail

You should have to use primaryTopic :
$str = file_get_contents('http://data.companieshouse.gov.uk/doc/company/02050399.json');
$json = json_decode($str, true);
$companyname = $json["primaryTopic"]["CompanyName"];
print $companyname;
Output will : ZENITH PRINT (UK) LIMITED

I think you had a mistake at 'primary topic' key. The key-name i saw in the response is 'primaryTopic'. Could you please check again?

Related

php json decode/parsing poloniex API

I am trying to run a php script in terminal to get a organized reply of cryptocurrency data. the full JSON array can be viewed at https://poloniex.com/public?command=returnTicker. The nested array isnt stacked with [] and parsing this format is becoming troublesome.
here is the code i used:
$fgc = json_decode(file_get_contents("https://poloniex.com/public?command=returnTicker"), true);
echo "Last Price: $".$fgc["last"]." Ask: ".$fgc["lowestAsk"]." Bid: ".$fgc["highestBid"];
echo PHP_EOL;
This is the error it gives me:
PHP Notice: Undefined index:
I have a feeling i need to define each coin however im not sure how to parse it.
other code i have tried:
$fgc = json_decode(file_get_contents("https://poloniex.com/public?command=returnTicker"), true);
$data = $fgc["BTC_BCN"];
foreach($data as $details){
echo "".$details["last"]." ".$details["lowestAsk"];
echo " ".$details["highestBid"];
echo PHP_EOL;
}
The error for this code is:
PHP Warning: Illegal string offset
Please help me understand how to parse this format. Thank you.

How to use Nominatim API through PHP to retrieve latitude and longitude?

Below is the code that I am currently using in which I pass an address to the function and the Nominatim API should return a JSON from which I could retrieve the latitude and longitude of the address from.
function geocode($address){
// url encode the address
$address = urlencode($address);
$url = 'http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1';
// get the json response
$resp_json = file_get_contents($url);
// decode the json
$resp = json_decode($resp_json, true);
// get the important data
$lati = $resp['lat'];
$longi = $resp['lon'];
// put the data in the array
$data_arr = array();
array_push(
$data_arr,
$lati,
$longi
);
return $data_arr;
}
The problem with it is that I always end up with an Internal Server Error. I have checked the Logs and this constantly gets repeated:
[[DATE] America/New_York] PHP Notice: Undefined index: title in [...php] on line [...]
[[DATE] America/New_York] PHP Notice: Undefined variable: area in [...php] on line [...]
What could be the issue here? Is it because of the _ in New_York? I have tried using str_replace to swap that with a + but that doesn't seem to work and the same error is still returned.
Also, the URL works fine since I have tested it out through JavaScript and manually (though {$address} was replaced with an actual address).
Would really appreciate any help with this, thank you!
Edit
This has now been fixed. The problem seems to be with Nominatim not being able to pickup certain values and so returns an error as a result
The errors you have mentioned don't appear to relate to the code you posted given the variables title and area are not present. I can provide some help for the geocode function you posted.
The main issue is that there are single quotes around the $url string - this means that $address is not injected into the string and the requests is for the lat/long of "$address". Using double quotes resolves this issue:
$url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";
Secondly, the response contains an array of arrays (if were not for the limit parameter more than one result might be expected). So when fetch the details out of the response, look in $resp[0] rather than just $resp.
// get the important data
$lati = $resp[0]['lat'];
$longi = $resp[0]['lon'];
In full, with some abbreviation of the array building at the end for simplicity:
function geocode($address){
// url encode the address
$address = urlencode($address);
$url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";
// get the json response
$resp_json = file_get_contents($url);
// decode the json
$resp = json_decode($resp_json, true);
return array($resp[0]['lat'], $resp[0]['lon']);
}
Once you are happy it works, I'd recommend adding in some error handling for both the http request and decoding/returning of the response.

php json_decode not working on json array

I have been searching the internet for hours now, and i can't figure it out.
<?php
$json = '{"pages":[{"name": "Page1","inputs":[{"title": "Catagory","name": "catagory","type": "radio","options":[{"name": "Paper","value": "paper"}{"name": "Letter","value": "letter"}]}{"title": "Title","name": "title","type": "text"}{"title": "File","name": "file","type": "file","fileName": "?pages[0].inputs[0]"}{"title": "Submit","type": "submit"}]}]}';
$result = json_decode($json, true);
var_dump($result);
echo $result['pages'][0]['name'];
echo $pages[0]['name'];
?>
Im just simply trying to parse some json but the website says this:
NULL
Notice: Undefined variable: pages in C:\Users\hazzj\Desktop\Stuff\Apache-Server\htdocs\WMS\Author\submit\test.php on line 7
You'd missed out commas between strings {}. Use this modified $json variable:
$json = '{"pages":[{"name": "Page1","inputs":[{"title": "Catagory","name": "catagory","type": "radio","options":[{"name": "Paper","value": "paper"},{"name": "Letter","value": "letter"}]},{"title": "Title","name": "title","type": "text"},{"title": "File","name": "file","type": "file","fileName": "?pages[0].inputs[0]"},{"title": "Submit","type": "submit"}]}]}';
$result = json_decode($json, true);
echo $result['pages'][0]['name']; // Output: Page1
echo $pages[0]['name']; // Not sure what this $pages variable is

: Undefined property: stdClass::$usd in

Okay I am using a framework so I can pull database rows like: $username->thenthenameoftherow
But the row I want it to bet a variable because the variable is defined via a post method, I run that variable through an explode to get the first part, the text before the _
Yet when I run: and get currency like:
$coin = $_POST['coin'];
//currency they want to user
$currency = explode('_', $coin);
$username->$currency[1]
I can't set a hardcoded row for that, it has to be a userdefined viariable
I get the error:
Notice: Undefined property: stdClass::$usd in C:\xampp\htdocs\mvc\application\controllers\dashboard.php on line 193
Using mini mvc framework
Okay, for an exampple the post to set the $coin is BTC_USD I then explode it to remove the _ and get the 2nd part of the string which is USD I then want to get the USD table from my database by running the user query but I get that error.
Your code is basically:
$_tmp = $username->$currency;
$result = $_tmp[1];
Did you mean:
$_tmp = $currency[1];
$result = $username->$_tmp;
? Because if so, you want:
$result = $username->{$currency[1]};
do you mean
$username->currency[1]
without $ before currency

json from string to array using php

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);

Categories