I coding a whole day just to display the nested Data from JSON that i got from the Api Provider but nothings gonna change. It's always error! what should i do?
Here's my code hope you help me in this problem.
Imagine my name of json file is 05-03-21.json.
and here's the JSON Data
{
"result":"OK",
"data":{
"body":{
"header":"Manila, National Capital Region, Philippines",
"query":{
"destination":{
"id":"1004070",
"value":"Manila, National Capital Region, Philippines",
"resolvedLocation":"CITY:1004070:UNKNOWN:UNKNOWN"
}
},
"searchResults":{
"totalCount":1286,
"results":[
{
"id":438619,
"name":"OYO 653 Rosas Garden Hotel",
"starRating":3,
"urls":[
],
"address":{
"streetAddress":"1140 MH Del Pilar St., Ermita",
"extendedAddress":"",
"locality":"Manila",
"postalCode":"1000",
"region":"Manila",
"countryName":"Philippines",
"countryCode":"ph",
"obfuscate":false
},
"welcomeRewards":{
"collect":true
},
"guestReviews":{
"unformattedRating":7,
"rating":"7.0",
"total":29,
"scale":10,
"badge":"good",
"badgeText":"Good"
},
"landmarks":[
{
"label":"City centre",
"distance":"2.0 km"
},
{
"label":"Manila Bay",
"distance":"7.6 km"
}
],
"geoBullets":[
],
"ratePlan":{
"price":{
"current":"P1,287",
"exactCurrent":1286.71,
"old":"P2,383",
"summary":"excluding taxes & fees"
},
"features":{
"freeCancellation":false,
"paymentPreference":false,
"noCCRequired":false
},
"type":"EC"
},
"neighbourhood":"Ermita",
"deals":{
"specialDeal":{
"dealText":"Save 46%"
},
"priceReasoning":"DRR-446"
},
"messaging":[
],
"badging":[
],
"pimmsAttributes":"DoubleStamps|D13|TESCO",
"coordinate":{
"lat":14.578154,
"lon":120.979947
},
"providerType":"LOCAL",
"supplierHotelId":6457589,
"isAlternative":false,
"optimizedThumbUrls":{
"srpDesktop":"https:\/\/thumbnails.trvl-media.com\/uQm5oEf1djKsihiqX24-TfWhriQ=\/250x140\/smart\/filters:quality(60)\/images.trvl-media.com\/hotels\/7000000\/6460000\/6457600\/6457589\/b189dd23_z.jpg"
}
},
{
"id":756613600,
"name":"Astrotel Anonas",
"starRating":3,
"urls":[
],
"address":{
"streetAddress":"960 Aurora Boulevard",
"extendedAddress":"near LRT Anonas Station",
"locality":"Quezon City",
"postalCode":"",
"region":"",
"countryName":"Philippines",
"countryCode":"ph",
"obfuscate":false
},
"welcomeRewards":{
"collect":true
},
"guestReviews":{
"unformattedRating":4.8,
"rating":"4.8",
"total":40,
"scale":10
},
"landmarks":[
{
"label":"City centre",
"distance":"10 km"
},
{
"label":"Manila Bay",
"distance":"17 km"
}
],
"geoBullets":[
],
"ratePlan":{
"price":{
"current":"P1,295",
"exactCurrent":1294.64,
"summary":"excluding taxes & fees"
},
"features":{
"freeCancellation":false,
"paymentPreference":false,
"noCCRequired":false
},
"type":"EC"
},
"neighbourhood":"Quezon City",
"deals":[
],
"messaging":[
],
"badging":[
],
"pimmsAttributes":"DoubleStamps|D13|TESCO",
"coordinate":{
"lat":14.627763,
"lon":121.06376
},
"providerType":"LOCAL",
"supplierHotelId":23612925,
"isAlternative":false,
"optimizedThumbUrls":{
"srpDesktop":"https:\/\/thumbnails.trvl-media.com\/0GhZSM5K0XRDs9aaIYn2FuUBUqk=\/250x140\/smart\/filters:quality(60)\/images.trvl-media.com\/hotels\/24000000\/23620000\/23613000\/23612925\/c83bf0b0_z.jpg"
}
}
]
},
"common":{
"pointOfSale":{
"numberSeparators":",.",
"brandName":"Hotels.com"
},
"tracking":{
"omniture":{
"s.prop33":"D=v33",
"s.prop32":"D=v43",
"s.prop74":"search result with dates | ms shown | N",
"s.products":"MULTISOURCE;6457589,LOCAL;23612925,LOCAL;23612485",
"s.eVar16":"Mob :: aApp",
"s.eVar40":"D=v0",
"s.eVar41":"PHP",
"s.eVar63":"60acf7e5-d622-4a1a-8110-a1fac036b405",
"s.eVar42":"30|1|20210404|20210405",
"s.eVar4":"|SI:anonymous|VS:returnVisitor|HCR:notApplicable|FC:notApplicable|NS:unknown|TI:notApplicable|SM:notApplicable|IR:anonymous|",
"s.eVar43":"en_PH|HCOM_PH|ph.hotels.com",
"s.eVar3":"2|0",
"s.eVar22":"5|PHP|24:438619:2382.7900:1286.7100:1|24:756613600:1294.6400:1294.6400:0|24:756599520:1294.6400:1294.6400:0|24:2052351936:1442.6200:1298.3600:0|24:454367:2407.3200:1299.9500:0",
"s.eVar2":"Manila, National Capital Region, Philippines",
"s.eVar23":"5|PHP|24:1279267456:1446.4300:1301.7900:0|24:632077728:2176.8300:1306.1000:1|24:494528:1455.3600:1309.8200:0|24:633744:1311.4800:1311.4800:0|24:1841636192:1311.4800:1311.4800:0",
"s.eVar24":"MCTC=20;TU=NA;PDID=NULL;MVT=",
"s.eVar7":"30",
"s.server":"ph.hotels.com",
"s.eVar6":"1004070",
"s.prop29":"D=v42",
"s.eVar5":"1",
"s.prop27":"1f6f9be9-a413-4f39-874c-86385cfe9627",
"s.eVar9":"Price - low to high",
"s.prop21":"0",
"s.prop20":"2",
"s.eVar69":"Mob :: aApp",
"s.currencyCode":"PHP",
"s.eVar26":"US:NY:NEWYORK:501",
"s.eVar29":"Mob :: aApp",
"s.prop9":"1286",
"s.eVar95":"Unknown",
"s.prop7":"1252",
"s.eVar31":"D=v0",
"s.eVar32":"D=v0",
"s.eVar33":"search result with dates",
"s.eVar34":"H1871:007.002,M376:152.000,M904:000.000,M3736:000.000,M4200:000.000,M4440.2,M4869:001.000,M4952:036.001,M4961:001.000,M5184:001.000,M5342:000.000,M5663:000.000,M6388:000.000,M6775:000.000,M6779:000.000,M7015.1,M7192:000.000,M7215:000.000,M7296:000.000,M7305:000.000,M7353:000.000,M7362.0,M7384:000.000,M7552:023.001,M7561:000.000,M7763:000.000,M7765.2,M7870:000.000,M7895:000.000,M8336:000.000,M8347:019.002,M8483:000.000,M8485:007.001,M8692:000.000,M8693:000.000,M8698:000.000,M8708:000.000,M8714:000.000,M8718:000.000,M8758:000.000,M8915:000.000,M8928:000.000,M8952:000.000,M8954:000.000,M8976:000.000,M8992:000.000,M9004:000.000,M9035:000.000,M9065:000.000,M9220:000.000,M9281:000.000,M9282:000.000,M9297:000.000,M9301:000.000,M9351:000.000,M9420:000.000,M9431:000.000,M9469:000.000,M9549:000.000,M9567.1,M9691:000.000,M9693:000.000,M9699:000.000,M9716:000.000,M9729:000.000,M9752:000.000,M9771:000.000,M9853:000.000,M9857:000.000,M9864:000.000,M9924:000.000,M9927:000.000,M9945:000.000,M9961:000.000,M9971:000.000,M10001:000.000,M10007:000.000,M10010:000.000,M10013:002.001,M10068:000.000,M10121:000.000,M10125:000.000,M10137:001.001,M10148:000.000,M10155:000.000,M10248:000.000,M9215:001.000",
"s.eVar13":"389242",
"s.prop19":"1",
"s.events":"event324,event319,event320",
"s.prop18":"D=v6",
"s.prop5":"389242",
"s.prop15":"1",
"s.prop3":"Manila, National Capital Region, Philippines",
"s.prop14":"D=v7",
"s.prop36":"|SI:anonymous|VS:returnVisitor|HCR:notApplicable|FC:notApplicable|NS:unknown|TI:notApplicable|SM:notApplicable|IR:anonymous|",
"s.eVar93":"aws.us-west-2.unknown",
"s.prop2":"Price - low to high"
}
}
}
}
}
}
And here's my php code.
<?php
$filepath = '05-03-21.json';
$json_string = file_get_contents($filepath);
$json_data = json_decode($json_string,true);
$json_data = json_decode($json_string,true);
foreach ($json_data as $var_1 ) {
foreach ($var_1['searchResults'] as $var_2 ) {
echo "Hotel Name: ".$var_2['name']."<br>";
echo "Ratings: ".$var_2['starRating']."<br>";
echo "Location: ".$var_2['address']['locality']."<br>";
}
}
?>
All i wanna do is to display the Data with loop something like this.
Image here
just parse the correct array with :
foreach ($json_data['data']['body']['searchResults']['results'] as $var_1 ) {
echo "Hotel Name: ".$var_1['name']."<br>";
echo "Ratings: ".$var_1['starRating']."<br>";
echo "Location: ".$var_1['address']['locality']."<br />========<br />";
}
Related
I am new to PHP and have little experience with PHP arrays, I have this below JSON file.
$json2=
'{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"diagnosticsProfile": {
"bootDiagnostics": {
"storageUri": "http://{existing-storage-account-name}.blob.core.windows.net",
"enabled": true
}
}
}
}';
I want to update the values for 'location', 'vmSize','sku','publisher','offer' in the above JSON,
"location" : "eastus"
"vmSize" : "Standard_D3_v2"
"sku" : "20h1-evd"
"publisher" : "MicrosoftWindowsDesktop"
"offer" : "windows-10"
I have tried to do the following to this but I am nowhere near navigating the array correctly.
$arr = json_decode($json2, true);
print_r($arr);
Can anyone please help here?
Just try this code
<?php
$json2=
'{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"diagnosticsProfile": {
"bootDiagnostics": {
"storageUri": "http://{existing-storage-account-name}.blob.core.windows.net",
"enabled": true
}
}
}
}';
$arr = json_decode($json2, true);
$arr['location'] = "eastus";
$arr['properties']['hardwareProfile']['vmSize'] = "Standard_D3_v2";
$arr['properties']['storageProfile']['imageReference']['sku'] = "20h1-evd";
$arr['properties']['storageProfile']['imageReference']['publisher'] = "MicrosoftWindowsDesktop";
$arr['properties']['storageProfile']['imageReference']['offer'] = "WindowsServer";
$updatedJson = json_encode($arr);
print_r($updatedJson);
First you need to try json_decode to make an array from this json file and then based on the array schema you need to find the property that you want and update it and then again use the json_encode to make an json
I'm very new to coding.
I'm using PHP to get a JSON response from an API. The JSON response consists of Titles and URLs to pages on the web. The sample JSON response is at the bottom of the page.
How do I write each item in this JSON data using PHP to my HTML page in the body tag? I want to create HTML "a" tags with the text being the JSON name value and the href being the JSON url value for each item.
Where does the JSON data end up after I get it from the API using PHP, and then how do I access it and format it with PHP? I'm using PHP to keep my API access key server side so the client can't see it. Here is my code:
<?php
$accessKey = "12345678";
$endpoint = '*Imaginary API endpoint*';
$term = 'hi';
function APIResponse ($url, $key, $query) {
$headers = "Ocp-Apim-Subscription-Key: $key\r\n";
$options = array ('http' => array (
'header' => $headers,
'method' => 'GET'));
$context = stream_context_create($options);
$result = file_get_contents($url . "?q=" . urlencode($query), false, $context);
$headers = array();
foreach ($http_response_header as $k => $v) {
$h = explode(":", $v, 2);
if (isset($h[1]))
if (preg_match("/^APIs-/", $h[0]) || preg_match("/^X-MSEdge-/", $h[0]))
$headers[trim($h[0])] = trim($h[1]);
}
return array($headers, $result);
}
if (strlen($accessKey) == 8) {
print "Searching the Web for: " . $term . "\n";
list($headers, $json) = APIResponse($endpoint, $accessKey, $term);
print "\nRelevant Headers:\n\n";
foreach ($headers as $k => $v) {
print $k . ": " . $v . "\n";
}
print "\nJSON Response:\n\n";
echo json_encode(json_decode($json), JSON_PRETTY_PRINT);
} else {
print("Invalid API subscription key!\n");
print("Please paste yours into the source code.\n");
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<!-- This is the result I'm looking for -->
<?php echo JSON:webPages:value:id ?>
</body>
</html>
JSON Response:
{
"_type": "SearchResponse",
"queryContext": {
"originalQuery": "hi"
},
"webPages": {
"webSearchUrl": "https:\/\/imaginaryapi.com\/search?q=hi",
"totalEstimatedMatches": 65700000,
"value": [
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.0",
"name": "Hi | Define Hi at Dictionary.com",
"url": "https:\/\/www.dictionary.com\/browse\/hi",
"isFamilyFriendly": true,
"displayUrl": "https:\/\/www.dictionary.com\/browse\/hi",
"snippet": "After you insisted, you write that, \u201cno one from the crew would meet my eyes or say hi.\u201d",
"dateLastCrawled": "2018-10-09T15:57:00.0000000Z",
"language": "en",
"isNavigational": false
},
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.1",
"name": "Fors\u00ed\u00f0a | H\u00e1sk\u00f3li \u00cdslands",
"url": "https:\/\/www.hi.is\/",
"about": [
{
"name": "University of Iceland"
}
],
"isFamilyFriendly": true,
"displayUrl": "https:\/\/www.hi.is",
"snippet": "Opi\u00f0 fyrir ums\u00f3knir um innritun \u00ed H\u00e1sk\u00f3la \u00cdslands \u00e1 vormisseri 2019 - Takmarka\u00f0ur hluti n\u00e1mslei\u00f0a \u00ed bo\u00f0i. Ums\u00f3knarfrestur \u00ed framhaldsn\u00e1m til 15. okt\u00f3ber og grunnn\u00e1m til 30. n\u00f3vember",
"deepLinks": [
{
"name": "Vefp\u00f3stur",
"url": "https:\/\/www.hi.is\/haskolinn\/vefpostur"
},
{
"name": "Leit A\u00f0 Starfsf\u00f3lki",
"url": "https:\/\/www.hi.is\/starfsmannaleit"
},
{
"name": "S\u00e6kja Um N\u00e1m",
"url": "https:\/\/ugla.hi.is\/umsoknir\/index.php"
},
{
"name": "Endurmenntun H\u00ed",
"url": "https:\/\/www.hi.is\/nam\/endurmenntun_hi"
},
{
"name": "Stundat\u00f6flur",
"url": "https:\/\/www.hi.is\/laeknadeild\/stundatoflur"
},
{
"name": "Fr\u00e9ttir",
"url": "https:\/\/www.hi.is\/frettir"
}
],
"dateLastCrawled": "2018-10-10T18:35:00.0000000Z",
"language": "is",
"isNavigational": false
},
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.2",
"name": "Hi | Definition of Hi by Merriam-Webster",
"url": "https:\/\/www.merriam-webster.com\/dictionary\/hi",
"isFamilyFriendly": true,
"displayUrl": "https:\/\/www.merriam-webster.com\/dictionary\/hi",
"snippet": "These example sentences are selected automatically from various online news sources to reflect current usage of the word 'hi.' Views expressed in the examples do not represent the opinion of Merriam-Webster or its editors.",
"dateLastCrawled": "2018-10-10T10:35:00.0000000Z",
"language": "en",
"isNavigational": false
},
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.3",
"name": "HI - Wikipedia",
"url": "https:\/\/en.wikipedia.org\/wiki\/HI",
"isFamilyFriendly": true,
"displayUrl": "https:\/\/en.wikipedia.org\/wiki\/HI",
"snippet": "Hi (or Hello) is a frequent act of greeting or welcoming someone.HI or Hi may also refer to:",
"dateLastCrawled": "2018-10-10T15:53:00.0000000Z",
"language": "en",
"isNavigational": false
},
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.4",
"name": "Hi (#hi) | Twitter",
"url": "https:\/\/twitter.com\/hi",
"thumbnailUrl": "https:\/\/www.bing.com\/th?id=OIP.PqKuxRwx55VE6E--5HFwKQAAAA&pid=Api",
"about": [
{
"name": "Hi"
},
{
"name": "Hi"
}
],
"isFamilyFriendly": true,
"displayUrl": "https:\/\/twitter.com\/hi",
"snippet": "The latest Tweets from Hi (#hi). BYEBYE Hi en daarmee ook dit account. We zijn nog wel in de lucht, maar niet actief. Voor servicevragen kun je terecht bij #KPNwebcare. Doei!. Den Haag, Zuid-Holland",
"dateLastCrawled": "2018-10-05T00:19:00.0000000Z",
"language": "en",
"isNavigational": false
},
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.5",
"name": "H\u00ef Ibiza - Brand-New Club in Ibiza, Spain",
"url": "https:\/\/www.hiibiza.com\/en",
"isFamilyFriendly": true,
"displayUrl": "https:\/\/www.hiibiza.com\/en",
"snippet": "H\u00ef Ibiza is the brand new club by Ushua\u00efa Entertainment located in the heart of Ibiza clubland, Playa d'en Bossa. The club will stay true to the open-minded spirit of Ibiza, bringing together music lovers to dance, discover and experience the magic of the White Isle.",
"dateLastCrawled": "2018-10-09T13:58:00.0000000Z",
"language": "en",
"isNavigational": false
},
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.6",
"name": "Danielle Bregoli is BHAD BHABIE \u201cHi Bich \/ Whachu Know ...",
"url": "https:\/\/www.youtube.com\/watch?v=1NyMSWqIJDQ",
"about": [
{
"name": "YouTube"
}
],
"isFamilyFriendly": true,
"displayUrl": "https:\/\/www.youtube.com\/watch?v=1NyMSWqIJDQ",
"snippet": "\ud83d\udea8STREAM \"Hi Bich\" \ufe0f https:\/\/Atlantic.lnk.to\/hibich \ud83d\udda4\ud83d\udc80\ud83c\udfa4\ud83d\udd25 new songs - \u24f5 video HI BICH & WHACHU KNOW by BHAD BHABIE aka Danielle Bregoli\ud83d\udda4\ud83d\udc45\ud83d\udc34\ud83c\udfc1 produced by Ronn...",
"dateLastCrawled": "2018-10-08T04:50:00.0000000Z",
"language": "en",
"isNavigational": false
},
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.7",
"name": "Hi - Capture. Write. Publish",
"url": "http:\/\/hitotoki.org\/",
"isFamilyFriendly": true,
"displayUrl": "hitotoki.org",
"snippet": "pancakes, Hi Meta, writing Full stack writing (and publishing): Welcome to Hi by Craig Mod. Tokyo \u2014 We\u2019d like to welcome you to Hi: A community of writers, journalists, journalers, illustrators, photographers, travelers, poets, and musicians exploring the world, and sharing those explorations throug...",
"dateLastCrawled": "2018-10-10T20:13:00.0000000Z",
"language": "en",
"isNavigational": false
},
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.8",
"name": "Hi - definition of hi by The Free Dictionary",
"url": "https:\/\/www.thefreedictionary.com\/hi",
"isFamilyFriendly": true,
"displayUrl": "https:\/\/www.thefreedictionary.com\/hi",
"snippet": "2. HI - a state in the United States in the central Pacific on the Hawaiian Islands",
"dateLastCrawled": "2018-10-09T09:35:00.0000000Z",
"language": "en",
"isNavigational": false
},
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.9",
"name": "Hi, Hi, Hi - Wikipedia",
"url": "https:\/\/en.wikipedia.org\/wiki\/Hi,_Hi,_Hi",
"about": [
{
"name": "Hi, Hi, Hi"
},
{
"name": "Hi, Hi, Hi"
},
{
"name": "Hi, Hi, Hi"
}
],
"isFamilyFriendly": true,
"displayUrl": "https:\/\/en.wikipedia.org\/wiki\/Hi,_Hi,_Hi",
"snippet": "\"Hi, Hi, Hi\" is a song written by Paul and Linda McCartney and performed by Wings. It was released as a double A-side single with \"C Moon\" in 1972.The song was recorded around the same time as \"C Moon\", in November 1972.",
"snippetAttribution": {
"license": {
"name": "CC-BY-SA",
"url": "http:\/\/creativecommons.org\/licenses\/by-sa\/3.0\/"
},
"licenseNotice": "Text under CC-BY-SA license"
},
"dateLastCrawled": "2018-10-10T20:41:00.0000000Z",
"language": "en",
"isNavigational": false
}
],
"someResultsRemoved": true
},
"rankingResponse": {
"mainline": {
"items": [
{
"answerType": "WebPages",
"resultIndex": 0,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.0"
}
},
{
"answerType": "WebPages",
"resultIndex": 1,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.1"
}
},
{
"answerType": "WebPages",
"resultIndex": 2,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.2"
}
},
{
"answerType": "WebPages",
"resultIndex": 3,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.3"
}
},
{
"answerType": "WebPages",
"resultIndex": 4,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.4"
}
},
{
"answerType": "WebPages",
"resultIndex": 5,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.5"
}
},
{
"answerType": "WebPages",
"resultIndex": 6,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.6"
}
},
{
"answerType": "WebPages",
"resultIndex": 7,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.7"
}
},
{
"answerType": "WebPages",
"resultIndex": 8,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.8"
}
},
{
"answerType": "WebPages",
"resultIndex": 9,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.9"
}
},
{
"answerType": "RelatedSearches",
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#RelatedSearches"
}
}
]
}
}
}
To print the data, you can use:
$result = json_decode ( $json, true);
foreach ( $result["webPages"]["value"] as $data)
{
echo "" . $data["name"] . "\n";
}
I like to use json_decode() method returning array instead of object, using true as second parameter, but you can also use it as object if you prefer.
Try this in the javascript section...
document.body.onload = addLink;
function addLink () {
// FIRST method : Embedding php in javascripts
<?php foreach(json_encode($json)->webPages->value as $value) { ?>
// Create a new markup
var newContent = $('<?php echo $value->id ?>');
// And add the text node to your div by it's class / id
$('.link').appendChild(newContent);
<?php } ?>
//////////////
// ...OR... //
//////////////
// SECOND method : Pass php variable (in this case it's JSON object) into javascripts
var json = <? echo json_encode($json)->webPages->value ?>;
json.forEach(function(value){
// Create a new markup
var newContent = $('' + value.id + '');
// And add the text node to your div by it's class / id
$('.link').appendChild(newContent);
});
}
Hopefully it works, because I'm not a daily php coder.
I have data type like below. But I want to get the 'errors' key and 'errors.message' value.
[
{
"payout_item_id":"HIDDEN",
"transaction_id":"HIDDEN",
"transaction_status":"UNCLAIMED",
"payout_item_fee":{
"currency":"USD",
"value":"10.25"
},
"payout_batch_id":"HIDDEN",
"payout_item":{
"amount":{
"currency":"USD",
"value":"10.00"
},
"note":"Thanks for your patronage",
"receiver":"HIDDEN#gmail.com",
"recipient_type":"EMAIL",
"sender_item_id":"1510369638"
},
"time_processed":"2017-11-11T03:07:26Z",
"errors":{
"name":"RECEIVER_UNCONFIRMED",
"message":"Receiver is unconfirmed",
"information_link":"https:\/\/developer.paypal.com\/docs\/api\/payments.payouts-batch\/#errors"
},
"links":[
{
"href":"https:\/\/api.sandbox.paypal.com\/v1\/payments\/payouts-item\/HIDDEN",
"rel":"item",
"method":"GET"
}
]
}
]
I have tried to store the code in variable ($get_errors) and then call 'errors' key like this. but the code is not working.
return $get_errors['errors'];
return $get_errors->errors;
Thanks.
Try to convert your JSON data to array then fetch the desired result from the array Try the following maybe it's work for you
$getError = '[
{
"payout_item_id":"HIDDEN",
"transaction_id":"HIDDEN",
"transaction_status":"UNCLAIMED",
"payout_item_fee":{
"currency":"USD",
"value":"10.25"
},
"payout_batch_id":"HIDDEN",
"payout_item":{
"amount":{
"currency":"USD",
"value":"10.00"
},
"note":"Thanks for your patronage",
"receiver":"HIDDEN#gmail.com",
"recipient_type":"EMAIL",
"sender_item_id":"1510369638"
},
"time_processed":"2017-11-11T03:07:26Z",
"errors":{
"name":"RECEIVER_UNCONFIRMED",
"message":"Receiver is unconfirmed",
"information_link":"https:\/\/developer.paypal.com\/docs\/api\/payments.payouts-batch\/#errors"
},
"links":[
{
"href":"https:\/\/api.sandbox.paypal.com\/v1\/payments\/payouts-item\/HIDDEN",
"rel":"item",
"method":"GET"
}
]
}
]';
$array_getError = json_decode($getError,true);
var_dump($array_getError[0]["errors"]);
This is Json type. So you have to decode json. Then you can geta data from it
$json = '[
{
"payout_item_id":"HIDDEN",
"transaction_id":"HIDDEN",
"transaction_status":"UNCLAIMED",
"payout_item_fee":{
"currency":"USD",
"value":"10.25"
},
"payout_batch_id":"HIDDEN",
"payout_item":{
"amount":{
"currency":"USD",
"value":"10.00"
},
"note":"Thanks for your patronage",
"receiver":"HIDDEN#gmail.com",
"recipient_type":"EMAIL",
"sender_item_id":"1510369638"
},
"time_processed":"2017-11-11T03:07:26Z",
"errors":{
"name":"RECEIVER_UNCONFIRMED",
"message":"Receiver is unconfirmed",
"information_link":"https:\/\/developer.paypal.com\/docs\/api\/payments.payouts-batch\/#errors"
},
"links":[
{
"href":"https:\/\/api.sandbox.paypal.com\/v1\/payments\/payouts-item\/HIDDEN",
"rel":"item",
"method":"GET"
}
]
}
]';
$data = json_decode($json,true);
echo $data[0]['errors']['message'];
DEMO
$x = '[
{
"payout_item_id":"HIDDEN",
"transaction_id":"HIDDEN",
"transaction_status":"UNCLAIMED",
"payout_item_fee":{
"currency":"USD",
"value":"10.25"
},
"payout_batch_id":"HIDDEN",
"payout_item":{
"amount":{
"currency":"USD",
"value":"10.00"
},
"note":"Thanks for your patronage",
"receiver":"HIDDEN#gmail.com",
"recipient_type":"EMAIL",
"sender_item_id":"1510369638"
},
"time_processed":"2017-11-11T03:07:26Z",
"errors":{
"name":"RECEIVER_UNCONFIRMED",
"message":"Receiver is unconfirmed",
"information_link":"https:\/\/developer.paypal.com\/docs\/api\/payments.payouts-batch\/#errors"
},
"links":[
{
"href":"https:\/\/api.sandbox.paypal.com\/v1\/payments\/payouts-item\/HIDDEN",
"rel":"item",
"method":"GET"
}
]
}
]';
$errors = (json_decode($x)[0]->errors);
I use json_decode() to parse a json feed and everything works just fine until I come to the array (media) that keeps digits as key instead of letters. I have tryed everything but all I get is different errors when it comes to this array (media)
The media array contains links to images and I just need the first image in every media array really. But the array can keep random digits in different order for the image links.
But the main problem is that I can't print this key, even if I know the name of it is "10" for example.
My second problem is that I never know the digits of the first image.
I would be very grateful if I can get help with this.
My code:
$data = json_decode($json_obj);
foreach($data->events as $event) {
echo $event->eventDateTime.'<br>'; //works
echo $event->eventId.'<br>'; //works
echo $event->title->eventTitleText.'<br>'; //works
echo strtoupper($event->venue->city).'<br>'; //works
echo $event->venue->title.'<br>'; //works
echo $event->ticketing->url.'<br>'; //works
echo $event->media->10.'<br>'; // Does NOT work
}
Below is a complete json feed that contains just 1 event.
{
"meta":{
"total":117,
"locale":"en-US",
"page":1,
"rows":1
},
"events":[
{
"-----":"252975",
"modifiedUTC":"2014-08-29T17:23:21",
"locale":"en-US",
"localeAvailable":{
"1":"sv-SE"
},
"title":{
"presentedBy":null,
"headliners":"<a href=\"http:\/\/www....\/artists\/251396\/djurgarden-hockey\">Djurg\u00e5rden Hockey<\/a> - Eisb\u00e4ren Berlin",
"supporting":null,
"supportingText":null,
"tour":"Champions Hockey League",
"eventTitle":"<a href=\"http:\/\/www....\/artists\/251396\/djurgarden-hockey\">Djurg\u00e5rden Hockey<\/a> - Eisb\u00e4ren Berlin",
"eventTitleText":"Djurg\u00e5rden Hockey - Eisb\u00e4ren Berlin"
},
"age":null,
"currency":"SEK",
"currencySymbol":null,
"eventDateTime":"2014-09-05T20:05:00",
"eventDateTimeZone":"Europe\/Stockholm",
"eventDateTimeUTC":"2014-09-05T18:05:00",
"eventDateTimeISO":"2014-09-05T20:05:00+02:00",
"dateOnly":false,
"additionalDates":[
],
"doorDateTime":null,
"doorDateTimeUTC":null,
"announceDateTime":"2014-08-04T10:00:00",
"announceDateTimeTimeZone":"Europe\/Stockholm",
"announceDateTimeUTC":"2014-08-04T08:00:00",
"presaleDateTime":null,
"presaleDateTimeTimeZone":null,
"presaleDateTimeUTC":null,
"presaleEndDateTime":null,
"presaleEndDateTimeTimeZone":null,
"presaleEndDateTimeUTC":null,
"onsaleDateTime":"2014-08-06T09:00:00",
"onsaleDateTimeTimeZone":"Europe\/Stockholm",
"onsaleDateTimeUTC":"2014-08-06T07:00:00",
"ticketing":{
"statusId":1,
"status":"Buy Tickets",
"callToAction":"Get your tickets today!",
"callToActionEnabled":false,
"url":"http:\/\/www....\/events\/252975\/djurgarden-hockey-eisbaren-berlin-tickets",
"eventUrl":"http:\/\/www....\/events\/252975\/djurgarden-hockey-eisbaren-berlin-tickets",
"ticketLinkExists":true
},
"ticketPrice":"120.00 kr - 170.00 kr",
"doorPrice":null,
"bio":null,
"description":null,
"minorCategoryId1":"34",
"minorCategoryId2":null,
"minorCategoryId3":null,
"majorCategoryId1":"3",
"majorCategoryId2":null,
"majorCategoryId3":null,
"venue":{
"venueId":"101916",
"locale":"en-US",
"localeAvailable":{
"1":"en-US",
"2":"sv-SE"
},
"title":"Hovet",
"address_line":"Globentorget 2, Stockholm, Sweden 121 27",
"address":"Globentorget 2",
"city":"Stockholm",
"state":null,
"postalCode":"121 27",
"country":"Sweden",
"url":"http:\/\/www....\/venues\/101916\/hovet-stockholm-tickets",
"urlSlug":"hovet-stockholm-tickets",
"venueUrl":"http:\/\/www.globearenas.se\/archive\/pages\/18711\/hovet.aspx",
"phone1":"0771-31 00 00",
"phone2":null,
"alias":null,
"parking":null,
"boxOffice":null,
"directions":null,
"longitude":"18.0808159",
"latitude":"59.2941674",
"timezone":"Europe\/Stockholm",
"ada":null,
"keywords":[
],
"skinCode":"sga",
"currency":"SEK",
"media":{
"10":{
"media_id":"29254",
"width":318,
"height":187,
"file_name":"http:\/\/........net\/10-08172012-502e82fe803bf.jpeg"
},
"11":{
"media_id":"29256",
"width":238,
"height":140,
"file_name":"http:\/\/........net\/11-08172012-502e82fe8f5a7.jpeg"
},
"14":{
"media_id":"29258",
"width":608,
"height":252,
"file_name":"http:\/\/........net\/14-08172012-502e83abb9512.jpeg"
},
"12":{
"media_id":"29255",
"width":134,
"height":79,
"file_name":"http:\/\/........net\/12-08172012-502e82fe88c58.jpeg"
}
},
"links":[
{
"link_id":976779,
"link_title":null,
"link_type_id":"23",
"link_href":"http:\/\/www.marriott.com\/search\/submitSearch.mi?searchType=InCity&formType=InCity&marriottBrands=BR&destinationAddress.city=Stockholm&destinationAddress.stateProvince=&destinationAddress.country=SE"
}
]
},
"tour":[
],
"promoters":null,
"associations":{
"performerIds":[
"251396"
],
"headliners":[
{
"performerId":"251396",
"locale":"en-US",
"localeAvailable":{
"1":"en-US"
},
"name":"Djurg\u00e5rden Hockey",
"minorCategoryText":"Hockey",
"minorCategoryId":"34",
"minorCategory1Id":"34",
"minorCategory2Id":null,
"minorCategory3Id":null,
"minorCategoryUrl":"http:\/\/www....\/browse\/sports\/hockey",
"majorCategoryText":"Sports",
"major_category_id":"3",
"majorCategory1Id":"3",
"majorCategory2Id":null,
"majorCategory3Id":null,
"majorCategoryUrl":"http:\/\/www....\/browse\/sports",
"keywords":[
"DIF",
"Djurgarden"
],
"bio":null,
"shortBio":null,
"aliases":null,
"url":"http:\/\/www....\/artists\/251396\/djurgarden-hockey-tickets",
"urlSlug":"djurgarden-hockey-tickets",
"media":{
"7":{
"media_id":"149467",
"width":220,
"height":220,
"file_name":"http:\/\/........net\/djurgarden-hockey_11-26-13_7_5294e45990e1f.jpg"
},
"24":{
"media_id":"149463",
"width":322,
"height":322,
"file_name":"http:\/\/........net\/djurgarden-hockey_11-26-13_24_5294e45974caa.jpg"
},
"6":{
"media_id":"149465",
"width":238,
"height":140,
"file_name":"http:\/\/........net\/djurgarden-hockey_11-26-13_6_5294e459867f5.jpg"
},
"5":{
"media_id":"149466",
"width":318,
"height":187,
"file_name":"http:\/\/........net\/djurgarden-hockey_11-26-13_5_5294e4598bec3.jpg"
},
"9":{
"media_id":"149464",
"width":134,
"height":79,
"file_name":"http:\/\/........net\/djurgarden-hockey_11-26-13_9_5294e45981552.jpg"
}
},
"events":[
],
"links":[
{
"link_id":976320,
"link_title":null,
"link_type_id":"13",
"link_href":"https:\/\/twitter.com\/difhockeyse"
},
{
"link_id":976321,
"link_title":null,
"link_type_id":"12",
"link_href":"https:\/\/www.facebook.com\/DJURGARDEN"
}
]
}
],
"supportingActs":[
]
},
"media":[
],
"relatedMedia":{
"1":{
"media_id":"149466",
"width":318,
"height":187,
"file_name":"http:\/\/........net\/djurgarden-hockey_11-26-13_5_5294e4598bec3.jpg"
},
"2":{
"media_id":"149465",
"width":238,
"height":140,
"file_name":"http:\/\/........net\/djurgarden-hockey_11-26-13_6_5294e459867f5.jpg"
},
"3":{
"media_id":"149467",
"width":220,
"height":220,
"file_name":"http:\/\/........net\/djurgarden-hockey_11-26-13_7_5294e45990e1f.jpg"
},
"4":{
"media_id":"149464",
"width":134,
"height":79,
"file_name":"http:\/\/........net\/djurgarden-hockey_11-26-13_9_5294e45981552.jpg"
},
"23":{
"media_id":"149463",
"width":322,
"height":322,
"file_name":"http:\/\/........net\/djurgarden-hockey_11-26-13_24_5294e45974caa.jpg"
},
"17":{
"media_id":0,
"width":"678",
"height":"399",
"file_name":"http:\/\/dc1tv648rdvbu.....net\/...\/bundles\/aeg...\/images\/defaults\/1\/1_678_399.png"
},
"18":{
"media_id":0,
"width":"564",
"height":"564",
"file_name":"http:\/\/dc1tv648rdvbu.....net\/...\/bundles\/aeg...\/images\/defaults\/1\/1_564_564.png"
}
},
"links":[
{
"link_id":976321,
"link_title":null,
"link_type_id":"12",
"link_href":"https:\/\/www.facebook.com\/DJURGARDEN"
},
{
"link_id":976320,
"link_title":null,
"link_type_id":"13",
"link_href":"https:\/\/twitter.com\/difhockeyse"
}
]
}
]
}
You need to use curly braces:
echo $event->media->{10}->width;
If you do not know what the properties will be called, you can iterate them in a nested loop:
foreach($event->media as $media){
echo $media->width . '<br/>';
}
To just get the 1st property, if you do not intend to iterate them, you can use reset():
$first = reset($event->media);
echo $first->width;
Live (updated) example: http://codepad.viper-7.com/IU2wCy
I have been getting my facebook friends work history. But the result is an array whose content is as follows :
{
"id": "xxx",
"friends": {
"data": [
{
"name": "Indiarto Priadi",
"work": [
{
"employer": {
"id": "111178415566505",
"name": "Liputan 6 SCTV"
}
},
{
"employer": {
"id": "107900732566334",
"name": "SCTV"
}
}
],
"id": "502163984"
},
{
"name": "Agustin Kertawijaya",
"work": [
{
"employer": {
"id": "138215336225242",
"name": "Trader Corporation (Canada)"
},
"location": {
"id": "110941395597405",
"name": "Toronto, Ontario"
},
"position": {
"id": "168673399850791",
"name": "Desktop operator <Pre press>"
},
"start_date": "2006-06-01",
"end_date": "2008-06-01"
},
{
"employer": {
"id": "114464911939560",
"name": "Merrill Corporation Canada"
},
"location": {
"id": "110941395597405",
"name": "Toronto, Ontario"
},
"position": {
"id": "190075304347365",
"name": "Financial Print Project Manager"
},
"start_date": "2006-06-01",
"end_date": "2011-10-01"
}
],
"id": "511990261"
}
],
"paging": {
"next": "https://graph.facebook.com/1065251285/friends?limit=2&fields=name,work&offset=2&__after_id=511990261"
}
}
}
Now i want to display "only" the employer name on my page, but i can't find the way to do that.
Here is my code :
$userFriends = $facebook->api('/'.$userId.'/friends');
for($i=0;$i<=3;$i++){ //retrieved friends (max 4 persons)
$value=$userFriends["data"][$i];
echo "<div id='$value[id]'>";
$profile = $facebook->api("/".$value["id"]);
$friendsWork = $facebook->api("/".$value["id"]."?fields=work");
echo "<strong>".$profile["name"]."<br></strong>";
echo " <img src='https://graph.facebook.com/".$value["id"]."/picture'><br>";
echo "Username : ".$profile["username"]."<br>";
echo "Local : ".$profile["locale"]."<br>";
echo "Birthdate : ".$profile["birthday"]."<br>";
print_r($friendsWork); // <--- the result is an array
echo "<hr>";
echo "</div>";
}
Does anyone know how to display the company(employer) name only?
any answers would be greatly appreciated. Thank You
Here you go, nothing fancy, I just did what I said in my comment
$json = '{
"id": "xxx",
"friends": {
"data": [
{
"name": "Indiarto Priadi",
"work": [
{
"employer": {
"id": "111178415566505",
"name": "Liputan 6 SCTV"
}
},
{
"employer": {
"id": "107900732566334",
"name": "SCTV"
}
}
],
"id": "502163984"
},
{
"name": "Agustin Kertawijaya",
"work": [
{
"employer": {
"id": "138215336225242",
"name": "Trader Corporation (Canada)"
},
"location": {
"id": "110941395597405",
"name": "Toronto, Ontario"
},
"position": {
"id": "168673399850791",
"name": "Desktop operator <Pre press>"
},
"start_date": "2006-06-01",
"end_date": "2008-06-01"
},
{
"employer": {
"id": "114464911939560",
"name": "Merrill Corporation Canada"
},
"location": {
"id": "110941395597405",
"name": "Toronto, Ontario"
},
"position": {
"id": "190075304347365",
"name": "Financial Print Project Manager"
},
"start_date": "2006-06-01",
"end_date": "2011-10-01"
}
],
"id": "511990261"
}
],
"paging": {
"next": "https://graph.facebook.com/1065251285/friends?limit=2&fields=name,work&offset=2&__after_id=511990261"
}}}'; // remember the last two closing curlys, you left them out of the code block in the OP.
$obj = json_decode($json);
foreach ($obj->friends->data as $friend) {
echo '<h1>' . $friend->name . '</h1>';
foreach ($friend->work as $job) {
echo 'Employee: ' . $job->employer->name . '<br/>';
}
echo '<hr>';
}
Output:
Indiarto Priadi
Employee: Liputan 6 SCTV
Employee: SCTV
--------------------------------------
Agustin Kertawijaya
Employee: Trader Corporation (Canada)
Employee: Merrill Corporation Canada
--------------------------------------
You just have to parse the array you obtained, like this-
$userFriends = $facebook->api('/'.$userId.'/friends?fields=work,name');
foreach($userFriends['data'] as $friend)
{
$friend_name = $friend['name'];
$emp_name=array();
// list of all employers of this friend
if(isset($friend['work']))
{
foreach($friend['work'] as $work)
{
array_push($emp_name, $work['employer']['name']);
}
}
else
{
$emp_name = "N.A.";
}
}