i am getting a json response from a site,
then convert it into json decoded file, my code is
$author = $_POST['author_name'];
$author_name = str_replace(' ', '+', $author);
$term = $_POST['term'];
$term_search = str_replace(' ', '+', $term);
$country = $_POST['country'];
$entity = 'ebook';
$search_url = "https://itunes.apple.com/searchterm=".$term_search."&entity=".$entity."&country=".$country;
$data = file_get_contents($search_url);
$josn_decoded = json_decode($data, true);
$file_name = "searched_book.csv";
$fp = fopen($file_name, 'w');
foreach($josn_decoded['results'] as $search_result){
fputcsv($fp, $search_result);
}
fclose($fp);
the response of echo "<pre>"; print_r($josn_decoded) is like
<pre>Array
(
[resultCount] => 5
[results] => Array
(
[0] => Array
(
[artistId] => 673560392
[artistName] => Hanna Raskin
[kind] => ebook
[price] => 2.99
[description] => Yelp Help, written by professional food critic Hanna Raskin (Seattle Weekly, Dallas Observer).
[currency] => USD
[genres] => Array
(
[0] => Cookbooks, Food & Wine
[1] => Books
[2] => Computers & Internet
[3] => Internet
)
[genreIds] => Array
(
[0] => 9028
[1] => 38
[2] => 9027
[3] => 10020
)
[releaseDate] => 2013-07-06T07:00:00Z
[trackId] => 673560390
[trackName] => Yelp Help: How to Write Great Online Restaurant Reviews
[formattedPrice] => $2.99
[artistIds] => Array
(
[0] => 673560392
)
[artworkUrl60] => http://a2.mzstatic.com/us/r30/Publication/v4/30/fa/89/30fa8929-ba32-41fd-c046-bb660b2c886c/9781301327515.60x60-50.jpg
[artistViewUrl] => https://itunes.apple.com/us/artist/hanna-raskin/id673560392?mt=11&uo=4
[trackCensoredName] => Yelp Help: How to Write Great Online Restaurant Reviews
[fileSizeBytes] => 219793
[artworkUrl100] => http://a5.mzstatic.com/us/r30/Publication/v4/30/fa/89/30fa8929-ba32-41fd-c046-bb660b2c886c/9781301327515.100x100-75.jpg
[trackViewUrl] => https://itunes.apple.com/us/book/yelp-help-how-to-write-great/id673560390?mt=11&uo=4
)
[1] => Array
(
[artistId] => 413390948
[artistName] => Gradiva Couzin & Jennifer Grappone
[kind] => ebook
[price] => 1.99
[description] => While most businesses know the importance of online reviews on sites such as Yelp.com, they have no clue how to grab the reins and help shape the conversation around their service or product.
[currency] => USD
[genres] => Array
(
[0] => Industries & Professions
[1] => Books
[2] => Business & Personal Finance
)
[genreIds] => Array
(
[0] => 10005
[1] => 38
[2] => 9009
)
[releaseDate] => 2013-10-03T07:00:00Z
[trackId] => 737317739
[trackName] => Yelp for Business
[formattedPrice] => $1.99
[artistIds] => Array
(
[0] => 413390948
[1] => 413390943
)
[artworkUrl60] => http://a2.mzstatic.com/us/r30/Publication6/v4/48/d4/fe/48d4fe78-2668-0c25-02f2-0e1cf2c21983/9781118857731.60x60-50.jpg
[artistViewUrl] => https://itunes.apple.com/us/artist/gradiva-couzin-jennifer-grappone/id413390948?mt=11&uo=4
[trackCensoredName] => Yelp for Business
[fileSizeBytes] => 2703426
[artworkUrl100] => http://a4.mzstatic.com/us/r30/Publication6/v4/48/d4/fe/48d4fe78-2668-0c25-02f2-0e1cf2c21983/9781118857731.100x100-75.jpg
[trackViewUrl] => https://itunes.apple.com/us/book/yelp-for-business/id737317739?mt=11&uo=4
)
)
)
when i write it into csv file i get following error
Array to string conversion in D:\wamp\www\search_book\search_code.php on line 29
please guide me.. i am new to this
fputcsv only accept one dimension array, not multidimensional array. You have to convert the genres, genreIds, artistIds, etc into string. Maybe you need something like implode() method.
For example:
foreach($josn_decoded['results'] as $search_result) {
if (is_array($search_result)) {
$search_result = implode('|', $search_result);
}
fputcsv($fp, $search_result);
}
So in csv, your genres column be like Cookbooks, Food & Wine|Books|Business & Personal Finance.
Try this one :)
<?php
$json_str = "{'aintlist':[4,3,2,1], 'astringlist':['str1','str2']}";
$json_obj = json_decode ($json_str);
$fp = fopen('file.csv', 'w');
foreach ($json_obj as $fields)
{
fputcsv($fp, $fields);
}
fclose($fp);
?>
Related
I have the following problem.
I am trying to read a Json file but I am not getting the desired result. I have the following data.
I would like to read the features and there is a mistake in finding out somewhere.
I get the error message when reading out:
Warning: Illegal string offset 'features'
Output
Array
(
[objectIdFieldName] => OBJECTID
[uniqueIdField] => Array
(
[name] => OBJECTID
[isSystemMaintained] => 1
)
[globalIdFieldName] =>
[geometryProperties] => Array
(
[shapeAreaFieldName] => Shape__Area
[shapeLengthFieldName] => Shape__Length
[units] => esriMeters
)
[geometryType] => esriGeometryPolygon
[spatialReference] => Array
(
[wkid] => 4326
[latestWkid] => 4326
)
[fields] => Array
(
[0] => Array
(
[name] => GEN
[type] => esriFieldTypeString
[alias] => GEN
[sqlType] => sqlTypeOther
[length] => 33
[domain] =>
[defaultValue] =>
)
[1] => Array
(
[name] => cases
[type] => esriFieldTypeInteger
[alias] => Anzahl Fälle
[sqlType] => sqlTypeOther
[domain] =>
[defaultValue] =>
)
[2] => Array
(
[name] => deaths
[type] => esriFieldTypeInteger
[alias] => Anzahl Todesfälle
[sqlType] => sqlTypeOther
[domain] =>
[defaultValue] =>
)
)
[features] => Array
(
[0] => Array
(
[attributes] => Array
(
[GEN] => Celle
[cases] => 220
[deaths] => 15
)
...........
My Code
$url = "https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/RKI_Landkreisdaten/FeatureServer/0/query?where=GEN%20%3D%20%27CELLE%27&outFields=GEN,cases,deaths&outSR=4326&f=json";
$json = file_get_contents($url);
$data = json_decode($json,true); //decode json result as array and thenloop it
print '<pre>';
print_r($data);
foreach($data as $row){
echo $row['features']->$row['attributes']->$row['GEN'];
}
Where am I wrong in reading?
It only has to be read what is in parentheses right?
So actually features-> attributes-> Gen to get the GEN query
Let's try change to this.
foreach($data as $row){
echo $row['features'][0]['attributes']['GEN'];
}
Sorry this is my fault when seem does'nt read clearly your question.
With GEN attribute you don't use loop to get this value.
If you wanna get GEN only your code should be that.
$url = "https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/RKI_Landkreisdaten/FeatureServer/0/query?where=GEN%20%3D%20%27CELLE%27&outFields=GEN,cases,deaths&outSR=4326&f=json";
$json = file_get_contents($url);
$data = (array) json_decode($json, true); //decode json result as array and thenloop it
print '<pre>';
print_r($data);
echo $data['features']['attributes']['GEN'];
// foreach($data as $row){
// echo $row['features']->$row['attributes']->$row['GEN'];
// }
I am exporting data from mysqli to google firebase DB. In firebase table one of the column named siteGeoCode (latitude and longitude) having values like [17.426083,78.439241] in array format. But in mysqli table two separate columns are there for latitude and longitude. I am trying to fetch records like below and converting those to array format.
$emp_array = array();
$sel_query = "select companyId,countryCode,createdBy,createdDat,`latitude`,`longitude`,siteName,`status` from customers limit 0,3";
$res = mysqli_query($mysqliConn,$sel_query);
while($sel_row = mysqli_fetch_assoc($res))
{
$emp_array[] = $sel_row;
$lat_array['siteGeoCode'][0] = $sel_row['latitude'];
$lat_array['siteGeoCode'][1] = $sel_row['longitude'];
array_push($emp_array,$lat_array);
}
// output
[0] => Array
(
[companyId] => iArwfGLC1lE6x3lO24cb
[countryCode] => 91
[createdBy] => X54P6gVJ7dA4Fi2fjEmc
[createdDate] => 2019-08-20 00:58:08
[latitude] => 15.6070347
[longitude] => 79.6146273
[siteName] => Ongole
[status] => 1
)
[1] => Array
(
[siteGeoCode] => Array
(
[0] => 15.6070347
[1] => 79.6146273
)
)
[2] => Array
(
[companyId] => YPbhSLWQfAR6ThhszSAf
[countryCode] => 91
[createdBy] => iArwfGLC1lE6x3lO24cb
[createdDate] => 2019-09-10 22:37:08
[latitude] =>
[longitude] =>
[siteName] => Madhap
[status] =>
)
[3] => Array
(
[siteGeoCode] => Array
(
[0] =>
[1] =>
)
)
but my desired output should be like below
[0] => Array
(
[companyId] => iArwfGLC1lE6x3lO24cb
[countryCode] => 91
[createdBy] => X54P6gVJ7dA4Fi2fjEmc
[createdDate] => 2019-08-20 00:58:08
[siteGeoPoint] => Array
(
[0] => 15.6070347
[1] => 79.6146273
)
[siteName] => Ongole
[status] => 1
)
[1] => Array
(
[companyId] => YPbhSLWQfAR6ThhszSAf
[countryCode] => 91
[createdBy] => iArwfGLC1lE6x3lO24cb
[createdDate] => 2019-09-10 22:37:08
[siteGeoPoint] => Array
(
[0] =>
[1] =>
)
[siteName] => Madhap
[status] =>
)
How can I achieve this ? Any help would be greatly appreciated. Thanks in advance
If you are wanting to place the result of the latitude/longitude columns into the result grouped, do the manipulations to the row, then add it to your result set, abit like below.
$result = [];
while ($row = mysqli_fetch_assoc($res)) {
// group geo
$row['siteGeoCode'] = [
$row['latitude'],
$row['longitude']
];
// unset uneeded
unset($row['latitude'], $row['longitude']);
// place in result
$result[] = $row;
}
You can use following code.
$output_array = array();
while($sel_row = mysqli_fetch_assoc($res)) {
$output_array[] = array(
'companyId' => $sel_row['companyId'],
'countryCode' => $sel_row['countryCode'],
'createdBy' => $sel_row['createdBy'],
'createdDate' => $sel_row['createdDate'],
'siteGeoPoint' => array($sel_row['latitude'], $sel_row['longitude']),
'siteName' => $sel_row['siteName'],
'status' => $sel_row['status'],
);
}
print_r($output_array);
you can see the difference you've used the array and I did. From you output I guess you've print different arrays.
Hope the code get you desire result!
I have the following JSON format
Array (
[version] => 3
[status] => ok
[response] => Array (
[data] => Array (
[0] => Array (
[accessible_wheelchair] => 1
[address] => 200 5th Ave
[category_labels] => Array (
[0] => Array (
[0] => Social
[1] => Food and Dining
[2] => Restaurants
[3] => Italian
)
[1] => Array (
[0] => Social
[1] => Food and Dining
[2] => Restaurants
[3] => Steakhouses
)
[2] => Array (
[0] => Social
[1] => Entertainment
[2] => Music and Show Venues
)
)
[country] => us
)
)
[included_rows] => 20
)
)
I want to fetch the data from the data->[0] array.
I used the following code to insert the data into database
$newurl="/*the api link is here*/";
$json = file_get_contents($newurl);
$data = json_decode($json,true);
foreach($data as $value){
$value1=$value;//$value
foreach($value as $newValue){
foreach($newValue as $newValue1){
$name=$newValue1["name"];
$sql="insert into restaurant (name) values(".$name.");";
db_query($sql) or die("insert error");
}
}
}
But it cannot be able to insert the data.Please whether there is any other method to fetch the my desired data and store it in database.
where is restaurant name?
<?php
$newurl="/*the api link is here*/";
$json = file_get_contents($newurl);
if ($json)
{
if (!($response = json_decode(stripslashes($json), TRUE)))
{
die("invalid json format");
}
}
if (!empty($response['status']) && $response['status'] == "ok")
{
$data = $response['response']['data'];
for ($i=0; $i < count($data); $i++)
{
// in this step data 0 wich you want to extract
/*
[accessible_wheelchair] => 1
[address] => 200 5th Ave
[category_labels] => Array (
[0] => Array (
[0] => Social
[1] => Food and Dining
[2] => Restaurants
[3] => Italian
)
[1] => Array (
[0] => Social
[1] => Food and Dining
[2] => Restaurants
[3] => Steakhouses
)
[2] => Array (
[0] => Social
[1] => Entertainment
[2] => Music and Show Venues
)
)
*/
// but what i confused here is restaurant name? i don't see restaurant name here..
}
}
I been playing around with google chart for my project, and somehow I'm still cant figure out displaying multidimensional array (from database).
print_r() output:
Array
(
[0] => Array
(
[year] => 2000
[value] => 2766
[typeName] => Oil
)
[1] => Array
(
[year] => 2000
[value] => 3098
[typeName] => Gas
)
[2] => Array
(
[year] => 2000
[value] => 269814
[typeName] => Coal
)
[3] => Array
(
[year] => 1999
[value] => 2836
[typeName] => Oil
)
[4] => Array
(
[year] => 1999
[value] => 3150
[typeName] => Gas
)
[5] => Array
(
[year] => 1999
[value] => 257561
[typeName] => Coal
)
);
as google chart required data format, I want it to be something like this:
['Year' , 'Oil', 'Gas', 'Coal']
["2000", 2766, 3098, 269814],
["1999" 2836, 3150, 257561]
Can someone help me how to play around with the multidimensional?
Thanks!
You shuld convert this data into json. Just parse in this way to get the desired structure O(n)
$headers = array("year" => 0, "oil" => 1, "gas" => 2, "coal" => 3);
$response[] = array_map("ucfirst",array_keys($headers));
foreach($orig_array as $k => $item) {
$temp_data[$item['year']][0] = (string) $item['year'];
$temp_data[$item['year']][$headers[$item['typeName']]] = $item['value'];
if(4==count($temp_data[$item['year']])) $response[] = $temp_data[$item['year']];
}
$json_data = json_encode($response);
echo($json_data);
How would i get the value of a key in an array?
The array is done by google shopping api which is:
// Valid source values are "public", "cx:cse", and "gan:pid"
// See http://code.google.com/apis/shopping/search/v1/getting_started.html#products-feed
$source = "public";
// For more information about full text search with the shopping API, please
// see http://code.google.com/apis/shopping/search/v1/getting_started.html#text-search
$query = "\"mp3 player\" | ipod";
//The order in which the API returns products is defined by a ranking criterion.
// See http://code.google.com/apis/shopping/search/v1/getting_started.html#ranking
$ranking = "relevancy";
$results = $service->products->listProducts($source, array(
"country" => "UK",
"q" => $query,
"rankBy" => $ranking,
));
print "<h1>Shopping Results</h1><pre>" . print_r($results, true) . "</pre>";
I have the following array which outputs:
Shopping Results
Array
(
[kind] => shopping#products
[etag] => "*********"
[id] => tag:google.com,2010:shopping/products
[selfLink] => https://www.googleapis.com/shopping/search/v1/public/products?country=UK&q=iphone&rankBy=relevancy
[nextLink] => https://www.googleapis.com/shopping/search/v1/public/products?country=UK&q=iphone&rankBy=relevancy&startIndex=26
[totalItems] => 771622
[startIndex] => 1
[itemsPerPage] => 25
[currentItemCount] => 25
[requestId] => 0CMjH976CqbECFYNWtAodLRwAAA
[items] => Array
(
[0] => Array
(
[kind] => shopping#product
[id] => tag:google.com,2010:shopping/products/5735617/11254757413841304510
[selfLink] => https://www.googleapis.com/shopping/search/v1/public/products/5735617/gid/11254757413841304510
[product] => Array
(
[googleId] => 11254757413841304510
[author] => Array
(
[name] => Amazon.co.uk
[accountId] => 5735617
)
[creationTime] => 2012-05-04T05:03:50.000Z
[modificationTime] => 2012-07-20T02:02:16.000Z
[country] => GB
[language] => en
[title] => Apple iPod touch 8GB - Black - 4th Generation (Latest Model - Launched Sept 2010)
[description] => Apple iPod touch 8GB - Black - 4th Generation (Latest Model - Launched Sept 2010)
[link] => http://www.amazon.co.uk/dp/B0040GIZTI/ref=asc_df_B0040GIZTI8843997?smid=A1YZ4RXO7GUOYN&tag=googlecouk06-21&linkCode=asn&creative=22218&creativeASIN=B0040GIZTI
[brand] => Apple
[condition] => new
[gtin] => 00885909394739
[gtins] => Array
(
[0] => 00885909394739
)
[mpns] => Array
(
[0] => MC540BT/A
)
[inventories] => Array
(
[0] => Array
(
[channel] => online
[availability] => inStock
[price] => 135.95
[shipping] => 1.99
[currency] => GBP
)
)
[images] => Array
(
[0] => Array
(
[link] => http://ecx.images-amazon.com/images/I/41p2rNmazRL.jpg
[status] => available
)
)
)
)
[1] => Array
(
[kind] => shopping#product
[id] => tag:google.com,2010:shopping/products/5735617/4597224105326146239
[selfLink] => https://www.googleapis.com/shopping/search/v1/public/products/5735617/gid/4597224105326146239
[product] => Array
(
[googleId] => 4597224105326146239
[author] => Array
(
[name] => Amazon.co.uk
[accountId] => 5735617
)
[creationTime] => 2012-05-04T05:03:50.000Z
[modificationTime] => 2012-07-20T02:02:16.000Z
[country] => GB
[language] => en
[title] => SanDisk Sansa Clip+ 8GB MP3 Player with Radio and Expandable MicroSD/SDHC Slot - Black
[description] => 8 GB memory Digital FM-tuner with 40 preset radio stations Extendable microSD/microSDHC card slot
[link] => http://www.amazon.co.uk/dp/B002NX0ME6/ref=asc_df_B002NX0ME68843997?smid=A3P5ROKL5A1OLE&tag=googlecouk06-21&linkCode=asn&creative=22206&creativeASIN=B002NX0ME6
[brand] => SanDisk
[condition] => new
[gtin] => 00619659059989
[gtins] => Array
(
[0] => 00619659059989
)
[mpns] => Array
(
[0] => SDMX18-008G-E46K
)
[inventories] => Array
(
[0] => Array
(
[channel] => online
[availability] => inStock
[price] => 46.95
[shipping] => 0
[currency] => GBP
)
)
[images] => Array
(
[0] => Array
(
[link] => http://ecx.images-amazon.com/images/I/419U6bYDF1L.jpg
[status] => available
)
)
)
)
I don't need all this data i just need 3-4 of the keys but how would i access them? How would i echo the value of say [title] from each array?
This should work:
foreach( $results as $result)
foreach( $result['product'] as $product)
echo $product['title'];
You could either loop through the array like pointed out above or possibly use array_walk_recursive like this:
$title_array = array();
array_walk_recursive($input_array, 'find_titles');
function find_titles($value, $key) {
global $title_array;
if ($key == 'title') {
$title_array[] = $value;
}
}
This might be a better solution if you you are not certain what the structure of the input array will be (i.e. how many levels deep the key you are looking for is nested).
To output the title of each product in $results:
foreach ($results as $result) {
echo $result['product']['title'];
}
Consider using array_walk_recursive
Working example
<?php
$a = array("hai", array("ha"=>1, "hai"=>2, array("a"=>1, "b"=>2)));
function test($item, $key)
{
echo "$key holds $item\n";
}
array_walk_recursive($a, 'test');
0 holds hai
ha holds 1
hai holds 2
a holds 1
b holds 2
If you are interested only in title
Consider using foreach
foreach($results['item'] as $result) {
echo $result['product']['title'];
}