This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
I am using the following code to pull data from an API with JSON results.
// Open connection
$ch = curl_init();
// Make the curl call
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$head = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$data = json_decode($head,true);
foreach($data as $item) {
$name = $item['name'];
$description = $item['description'];
echo "NAME: $name DESCRIPTION: $description";
}
If I use print_r($head) I see all of the results so I know url, username, password is good, however the echo statement at the end of the code is not producing results.
Here is a sample of what the JSON looks like when I print_r($head). Some of it at least.
{"events":[{"eventId":5183191,"name":"The Rhythm Rockets - FREE","description":"Summer Concert Series - The Rhythm Rockets . .\nFREE. Look for a YELLOW balloon. Bring a chair. PLEASE BE ON TIME (6:00 PM!) TO SIT WITH THE GROUP. Allow time for street parking. Expect a crowd. Meetup at 6pm - Showtime is 7pm. Food, wine and beer will be on sale.\nIn case of inclement weather, concerts will be held indoors at the Lincoln Center, 935 Maple Avenue. For weather updates, call[masked] after 5:30 pm. If moved inside, there is no way we can sit together.","primaryImage":{"smallImageUrl":"https://domainnamestorage.blob.core.windows.net/portalimages/portalimages/71021444-d72d-456c-a419-36b61ead5259.small.png","mediumImageUrl":"https://domainnamestorage.blob.core.windows.net/portalimages/portalimages/71021444-d72d-456c-a419-36b61ead5259.medium.png","largeImageUrl":"https://domainnamestorage.blob.core.windows.net/portalimages/portalimages/71021444-d72d-456c-a419-36b61ead5259.large.png"},"categories":[{"categoryId":2,"parentCategoryId":null,"name":"Performing Arts"},{"categoryId":12,"parentCategoryId":null,"name":"Food & Drink"},{"categoryId":17,"parentCategoryId":2,"name":"Music"},{"categoryId":75,"parentCategoryId":12,"name":"Drinks"},{"categoryId":100,"parentCategoryId":17,"name":"Concerts"}],"location":{"latitude":41.792683,"longitude":-88.011765,"city":"Downers Grove","state":"IL","address":"1000 Grove St","country":"United States","locationName":"Fishel Park"},"instances":[{"startDateTime":"2018-08-21T18:00:00Z","endDateTime":null,"hasTime":true,"allDay":false}],"price":{"lowerPrice":null,"upperPrice":null,"free":false,"description":null},"lastUpdatedDate":"2018-07-26T02:20:49.686Z","popularity":null,"interest":50,"links":[{"isSponsor":false,"name":"Meetup","linkUrl":"https://www.meetup.com/Im-Not-Dead-Yet-50-plus/events/252406255/","logoUrl":null},{"isSponsor":true,"name":"I'm Not Dead Yet --- 50+ Meetup","linkUrl":"http://Meetup.com/Im-Not-Dead-Yet-50-plus","logoUrl":null},{"isSponsor":true,"name":"I'm Not Dead Yet --- 50+ Meetup","linkUrl":"http://Meetup.com/Im-Not-Dead-Yet-50-plus","logoUrl":null}],"previousEventIds":[],"seriesStart":"2018-08-21T18:00:00Z","seriesEnd":null,"url":"http://portal.domainname.com/m/FireVite#!/details/THE-RHYTHM-ROCKETS-FREE/5183191/2018-08-21T18","handPicked":false,"customField":null,"contact":{"organization":null,"name":null,"email":null,"phone":null},"media":null}
After your decode, $data will have an array called events with each element being the array you are trying to look at. try:
foreach ($data['events'] as $item)...
print_r() does not make sense forstring, but only for array and object.
it might be rather alike this (and maybe you have to use $data['events'] instead)
when using $data = json_decode($response); it would be $data->events:
$data = json_decode($response, true);
// die('<pre>'.print_r($data, true).'</pre>');
foreach($data['events'] as $key => $item) {
// $event_id = $data['events'][$key]['eventId'];
$event_id = $item['eventId'];
// $name = $data['events'][$key]['name'];
$name = $item['name'];
// $desc = $data['events'][$key]['description'];
$desc = $item['description'];
echo "KEY: $key, ID: $event_id, NAME: $name, DESCRIPTION: $desc";
}
those inline comments just indicate, what is actually being accessed.
Related
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed last year.
I am new to PHP and I am trying to build a joomla module that displays the current BTC Price.
I am using this API: https://api.coindesk.com/v1/bpi/currentprice.json
I cannot find out how to access the USD and EUR "rate". This is where I am currently (ignore the var_dump, I used it to verify I was receiving data):
<?php
$curl_handle = curl_init();
$url = "https://api.coindesk.com/v1/bpi/currentprice.json";
curl_setopt($curl_handle, CURLOPT_URL, $url);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
$curl_data = curl_exec($curl_handle);
curl_close($curl_handle);
$response_data = json_decode($curl_data);
//var_dump($response_data);
$user_data = $response_data;
foreach ($user_data as $user)
{
foreach ($user as $key => $value)
{
echo $key;
echo "<br />";
}
}
echo $response_data['bpi']['USD']['rate'];
This seems to work just fine. Will mark it as solved, leaving it as it might help someone...
I am a newbie developer trying to learn web development. I am currently working on this project where articles from a website get shared automatically to a viber public chat. I am facing this problem where I cannot put the URL in the media. I think this is because its json. I am not sure what I am doing wrong here. I have included.
<?php
$Tid = "-1";
if (isset($_GET['id'])) {
$Tid = $_GET['id'];
}
$url = 'https://chatapi.viber.com/pa/post';
$jsonData='{
"auth_token":"4750f56f26a7d2ed-f6b44b76f03d039a-9601b6c9d0d46813",
"from": "K9/C2Vz12r+afcwZaexiCg==",
"type":"url",
"media": "$thisID"
// I want to use $thisID as shown above. But when I
do so this error appears [ {"status":3,"status_message":"'media' field value is not a valid url."} ]
// When I use any full form url like https://google.com it works fine
}';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
?>
This would work as you are using a single quoted literal.
"media": "' . $thisID . '"
But you are always better to make a PHP array or Object and then use json_encode() to create the JSON String like this
$obj = new stdClass;
$obj->auth_token = "4750f56f26a7d2ed-f6b44b76f03d039a-9601b6c9d0d46813";
$obj->from = "K9/C2Vz12r+afcwZaexiCg==";
$obj->type = 'url';
$obj->media = $thisID;
$jsondata = json_encode($obj);
RESULT of echo $jsondata;
{"auth_token":"4750f56f26a7d2ed-f6b44b76f03d039a-9601b6c9d0d46813",
"from":"K9\/C2Vz12r+afcwZaexiCg==",
"type":"url",
"media":"-1"
}
I have a string in a json format, but this is giving invalid json format as i am querying it via php loops
{"a":"" works our ‘T’ logo into an intricately perforated pattern. logo — pattern. Height: .36"" (.9 cm) Length: .29"" (.7 cm) " " }
I need the output as
{"a":"works our ‘T’ logo into an intricately perforated pattern. logo †pattern. Height: .36 (.9 cm) Length: .29 (.7 cm)"}
(i think this should be the correct format)
I have tried str_replace ,but it is removing quotes from the start and end as well, and trim() method also removed all the double quotes in the string.
<?php
$a = "" works our ‘T’ logo into an intricately perforated pattern. logo — pattern. Height: .36"" (.9 cm) Length: .29"" (.7 cm) " " ;
echo str_replace('"',"",$a);
?>
and i m getting this error:
Line : 2, Error type : 4
Message : syntax error, unexpected 'works' (T_STRING)
Note: this value is fetched from the DB and i need it to post to some api so that they can get all the values from our api. and i really dnt want to make any changes in our database or our backend from where this value is coming.
Hint or little solution would help i think.
//To highlight more on what i m exactly doing with the json
//see the below code.
<?php
ini_set('max_execution_time', 0);
require __DIR__ . '/app/Mage.php';
umask(0);
Mage::app();
$collection = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect("name");
foreach($collection as $product){
$product_name = strip_tags($product->getName()); //get name of the product
$result = array();
foreach ($products as $product1) {
$label = array_reduce(
$someattrbute,
function ($carry, $item) use ($product1) {
return $carry . $product1->getAttributeText($item) . ' ';
},
''
);
$result[trim($label)] = $product1->getQty();
}
$product_sizeandquantity = json_encode($result); //result
$products_data.= "{";
$products_data.= '"product_name"'.":".'"'.$product_name.'",';
$products_data.= '"product_stock"'.":".'['.$product_sizeandquantity.'],';
$products_data.= "},";
$products_data = rtrim($products_data, ',');
$products_data.= "]";
//echo $products_data;
$url = 'https://www.yourdomain.com/products';
$api_key = 'mykey';
$sec_key = 'secretkey';
$data='scapi_key='.urlencode($api_key).'&scsecret_key='.urlencode($sec_key)."&products=".urlencode($products_data);
//echo $data;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded')
);
$response = curl_exec($ch);
curl_close($ch);
$arr = json_decode($response, true);
echo $arr;
?>
And this is the json i m getting and this is only for one product, but there are many,as it is foreach loop:
[{"product_name":"Flats", "product_stock":[{"38":"1.0000"}]}]
I think that this is valid json, but still want to know what can be done to pass it through the post request of curl in the above code, as error shows that its a json invalid error.
Note: Some of the products also has the height and sizes and content containing double quotes as shown above.
I am working on getting some xml data into a php variable so I can easily call it in my html webpage. I am using this code below:
$ch = curl_init();
$timeout = 5;
$url = "http://www.dictionaryapi.com/api/v1/references/collegiate/xml/define?key=0b03f103-f6a7-4bb1-9136-11ab4e7b5294";
$definition = simplexml_load_file($url);
echo $definition->entry[0]->def;
However my results are: .
I am not sure what I am doing wrong and I have followed the php manual, so I am guessing it is something obvious but I am just not understanding it correctly.
The actual xml results from that link used in cURL are visible by clicking the link below , I did not post it because it is rather long:
http://www.dictionaryapi.com/api/v1/references/sd3/xml/test?key=9d92e6bd-a94b-45c5-9128-bc0f0908103d
<?php
$ch = curl_init();
$timeout = 5;
$url = "http://www.dictionaryapi.com/api/v1/references/collegiate/xml/define?key=0b03f103-f6a7-4bb1-9136-11ab4e7b5294";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch); // you were missing a semicolon
$definition = new SimpleXMLElement($data);
echo '<pre>';
print_r($definition->entry[0]->def);
echo '</pre>';
// this returns the SimpleXML Object
// to get parts, you can do something like this...
foreach($definition->entry[0]->def[0] as $entry) {
echo $entry[0] . "<br />";
}
// which returns
transitive verb
14th century
1 a
:to determine or identify the essential qualities or meaning of
b
:to discover and set forth the meaning of (as a word)
c
:to create on a computer
2 a
:to fix or mark the limits of :
b
:to make distinct, clear, or detailed especially in outline
3
:
intransitive verb
:to make a
Working Demo
I'll try to be short: if you need more info, I'll tell you.
I'm using this code to get infos from Google Maps:
<?php
function getData($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0); //Change this to a 1 to return headers
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$url = 'http://maps.google.com/maps/geo?output=xml&q=' . urlencode($startPlace);
$url = 'http://maps.google.com/maps/api/geocode/json?sensor=false&gl=IT&address=' . urlencode($startPlace);
$xml = simplexml_load_string($this->getData($this->url)) or die("Error loading xml data");
$points = $xml->Response->Placemark->Point->coordinates;
$provincia = $xml->Response->Placemark->AddressDetails->Country->AdministrativeArea->SubAdministrativeArea->SubAdministrativeAreaName;
$regione =$xml->Response->Placemark->AddressDetails->Country->AdministrativeArea->AdministrativeAreaName;
echo $regione."<br>";
preg_match_all("/-*[0-9.]*(?=,)/", $points[0], $matches);
$longitude = $matches[0][0];
$latitude = $matches[0][2];
The code is used to retrieve infos about italian locations and till three days ago, all worked fine, but this morning I saw something strange: $regione returned by code ($xml->Response->Placemark->AddressDetails->Country->AdministrativeArea->AdministrativeAreaName;) had an english name.
Let's say the location found be a little town in Lombardia (where 'Lombardia' is the name of the Administrative Area), the Administartive Area name returned by Google Maps was no more 'Lombardia' but 'Lombardy'.
Since this data is used to search in a local database other places in the Administrative area and since the name used in the database is obviously italian name, application doesnìt work anymore.
I'll be grateful for any advice
The problem is solved using a different url, specifying language parameter:
'http://maps.google.com/maps/api/geocode/xml?sensor=false&language=IT&address=' . urlencode($startPlace);
This url type return correct results but defferently formed so it is necessary change the code to access the infos and put them into variables, but this solved my problem