how to storing json data to mysql with php - php

This is my example json data
[
{"kode":"AX5","harga":"6200","status":"1","nama":"AXIS 5"},
{"kode":"AX10","harga":"11250","status":"1","nama":"AXIS 10"},
{"kode":"AX25","harga":"25750","status":"1","nama":"AXIS 25"},
{"kode":"AX50","harga":"50800","status":"1","nama":"AXIS 50"}
]
and i want to save the data to mysql with php, field product_id, price, status, name, anyone can help me please
my problem is, i dont know better code for me in php

You could use PHP
json_decode()
function to convert that json string into PHP variables.
You could then get those values and save them to the MySQL Database;
Source json_decode PHP Manual

you can use json_decode(). it takes a JSON encoded string and converts it into a PHP variable.
<?php
$json_data = '[{"kode":"AX5","harga":"6200","status":"1","nama":"AXIS 5"},{"kode":"AX10","harga":"11250","status":"1","nama":"AXIS 10"},{"kode":"AX25","harga":"25750","status":"1","nama":"AXIS 25"},{"kode":"AX50","harga":"50800","status":"1","nama":"AXIS 50"}]';
$array_data = json_decode($json_data);
echo '<pre>';
print_r($array_data);
foreach ($array_data as $event) {
echo 'Product_id:' . $event->kode;
echo "<br>";
echo 'status:' . $event->status;
echo "<br>";
}
then output is
Array
(
[0] => stdClass Object
(
[kode] => AX5
[harga] => 6200
[status] => 1
[nama] => AXIS 5
)
[1] => stdClass Object
(
[kode] => AX10
[harga] => 11250
[status] => 1
[nama] => AXIS 10
)
[2] => stdClass Object
(
[kode] => AX25
[harga] => 25750
[status] => 1
[nama] => AXIS 25
)
[3] => stdClass Object
(
[kode] => AX50
[harga] => 50800
[status] => 1
[nama] => AXIS 50
)
)
Product_id:AX5
status:1
Product_id:AX10
status:1
Product_id:AX25
status:1
Product_id:AX50
status:1
for more information
http://php.net/manual/en/function.json-decode.php

Related

How do I get an element from JSON in PHP?

I have this output from a JSON. How can I get one element (for example "etternavn" ) into a PHP variable. This is the output I get for the whole thing:
stdClass Object (
[hitLinesBeforeFilter] => 1
[userID] => 632
[1] => stdClass Object (
[listing] => stdClass Object (
[table] => listing
[id] => 1402864
[duplicates] => Array (
[0] => stdClass Object (
[table] => listing
[id] => 1402864:0
[idlinje] => D1FIJFT000
[tlfnr] => 41428798
[etternavn] => Bumpy Bones Interactive Cornelius Gutsu
[veinavn] => Hans Nielsen Hauges vei
[husnr] => 48F
[postnr] => 1523
[virkkode] => N
[apparattype] => M
[kilde] => D
[foretaksnr] => 998209609
[bransjekode] => 15636
[prioritet] => 0
[kommunenr] => 104
[poststed] => Moss
[kommune] => Moss
[fylke] => Østfold
[landsdel] => Ø
[bransjebokmaal] => Internettdesign og programmering
[bransjenynorsk] => Internett design og programmering
)
)
)
)
[dummy] =>
)
The PHP code is the following:
$json = utf8_encode(file_get_contents($url, 'UTF-8'));
$data = json_decode($json);
print_r($data->result);
I have tried echo $data->etternavn;
I know this might be a simple question, sorry. I'm not good with coding.
You can do this:
<?php
$json = utf8_encode(file_get_contents($url, 'UTF-8'));
$data = json_decode($json, true);
print_r($data['result'][1]['listing']['duplicates'][0]['etternavn']);
?>
You have to traverse through this complex structure. To get etternavn you need to do this:
$data = json_decode($json);
echo $data->result->{1}->listing->duplicates->{0}->etternavn;
Or as suggested in comments, pass next parameter of json_decode to true. Which will convert it into array.
$data = json_decode($json, true);
echo $data['result'][1]['listing']['duplicates'][0]['etternavn'];

php - Parse Goole Books PI JSON [duplicate]

This question already has answers here:
Using Google Books API
(2 answers)
Closed 5 years ago.
I have written a PHP code to parse the data pobidd by GoogleBooks API
<?php
$isbn = "9781451648546"; // Steve Jobs book
$json = file_get_contents('https://www.googleapis.com/books/v1/volumes?q=isbn:'.$isbn);
$obj = json_decode($json, true);
echo $obj["volumeInfo"]["title"];
echo $obj["volumeInfo"]["title"];
echo $obj["volumeInfo"]["subtitle"];
echo $obj["volumeInfo"]["authors"];
echo $obj["volumeInfo"]["printType"];
echo $obj["volumeInfo"]["pageCount"];
echo $obj["volumeInfo"]["publisher"];
echo $obj["volumeInfo"]["publishedDate"];
echo $obj["accessInfo"]["webReaderLink"];
?>
When execute it, I get
Notice: Undefined index: volumeInfo in /storage/ssd3/164/2474164/public_html/dev/fetch/v2.php on line 8
for all the echo strings , so I re-checked all possible sources of problem without solution
You're accessing the array elements in the wrong way. Do var_dump($obj); or echo '<pre>'; print_r($obj); echo '</pre>'; to see the complete array structure. Your echo statements would be like this:
echo $obj['items'][0]["volumeInfo"]["title"] . '<br />';
// echo $obj['items'][0]["volumeInfo"]["subtitle"];
echo $obj['items'][0]["volumeInfo"]["authors"][0] . '<br />';
echo $obj['items'][0]["volumeInfo"]["printType"] . '<br />';
echo $obj['items'][0]["volumeInfo"]["pageCount"] . '<br />';
echo $obj['items'][0]["volumeInfo"]["publisher"] . '<br />';
echo $obj['items'][0]["volumeInfo"]["publishedDate"] . '<br />';
echo $obj['items'][0]["accessInfo"]["webReaderLink"] . '<br />';
Not sure whether you would be getting subtitle information along with the book details. If so, then please uncomment that line.
To my mind it is far easier to use the object notation for accessing the various properties of the JSON response rather than the clunky array syntax but you need to identify the correct location in the object/array heirarchy before attempting to access the sub-keys of it.
$isbn = "9781451648546"; // Steve Jobs book
$json = file_get_contents('https://www.googleapis.com/books/v1/volumes?q=isbn:'.$isbn);
$obj = json_decode( $json );
$items=$obj->items;
foreach( $items as $item ){
/* Main keys */
$vol=$item->volumeInfo;
$sales=$item->saleInfo;
$access=$item->accessInfo;
$info=$item->searchInfo;
/* subkeys */
$title=$vol->title;
$authors=implode( $vol->authors );
$type=$vol->printType;
/* etc */
echo $title, $authors, $type, '<br />';//etc
}
/* to clearly see the data structure try this: */
echo '<pre>',print_r($obj,true),'</pre>';
Will output
Steve JobsWalter IsaacsonBOOK
stdClass Object
(
[kind] => books#volumes
[totalItems] => 1
[items] => Array
(
[0] => stdClass Object
(
[kind] => books#volume
[id] => 8U2oAAAAQBAJ
[etag] => Cfd5hfOLjks
[selfLink] => https://www.googleapis.com/books/v1/volumes/8U2oAAAAQBAJ
[volumeInfo] => stdClass Object
(
[title] => Steve Jobs
[authors] => Array
(
[0] => Walter Isaacson
)
[publisher] => Simon and Schuster
[publishedDate] => 2011
[description] => Draws on more than forty interviews with Steve Jobs, as well as interviews with family members, friends, competitors, and colleagues to offer a look at the co-founder and leading creative force behind the Apple computer company.
[industryIdentifiers] => Array
(
[0] => stdClass Object
(
[type] => ISBN_13
[identifier] => 9781451648546
)
[1] => stdClass Object
(
[type] => ISBN_10
[identifier] => 1451648545
)
)
[readingModes] => stdClass Object
(
[text] =>
[image] =>
)
[pageCount] => 630
[printType] => BOOK
[categories] => Array
(
[0] => Biography & Autobiography
)
[averageRating] => 4
[ratingsCount] => 3904
[maturityRating] => NOT_MATURE
[allowAnonLogging] =>
[contentVersion] => 0.3.0.0.preview.0
[imageLinks] => stdClass Object
(
[smallThumbnail] => http://books.google.com/books/content?id=8U2oAAAAQBAJ&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api
[thumbnail] => http://books.google.com/books/content?id=8U2oAAAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api
)
[language] => en
[previewLink] => http://books.google.co.uk/books?id=8U2oAAAAQBAJ&printsec=frontcover&dq=isbn:9781451648546&hl=&cd=1&source=gbs_api
[infoLink] => http://books.google.co.uk/books?id=8U2oAAAAQBAJ&dq=isbn:9781451648546&hl=&source=gbs_api
[canonicalVolumeLink] => https://books.google.com/books/about/Steve_Jobs.html?hl=&id=8U2oAAAAQBAJ
)
[saleInfo] => stdClass Object
(
[country] => GB
[saleability] => NOT_FOR_SALE
[isEbook] =>
)
[accessInfo] => stdClass Object
(
[country] => GB
[viewability] => PARTIAL
[embeddable] => 1
[publicDomain] =>
[textToSpeechPermission] => ALLOWED_FOR_ACCESSIBILITY
[epub] => stdClass Object
(
[isAvailable] =>
)
[pdf] => stdClass Object
(
[isAvailable] =>
)
[webReaderLink] => http://play.google.com/books/reader?id=8U2oAAAAQBAJ&hl=&printsec=frontcover&source=gbs_api
[accessViewStatus] => SAMPLE
[quoteSharingAllowed] =>
)
[searchInfo] => stdClass Object
(
[textSnippet] => Draws on more than forty interviews with Steve Jobs, as well as interviews with family members, friends, competitors, and colleagues to offer a look at the co-founder and leading creative force behind the Apple computer company.
)
)
)
)

PHP - Access JSON data value in array

I'm sorry if this is newbie question but I don't understand how to access the [ids] value in the JSON array via PHP.
Why is this not working?
$jsonResponse = json_decode($response,true);
print $jsonResponse[2]["ids"];
This is the JSON array:
Array
(
[0] => analytics#gaData
[1] => https://www.googleapis.com/analytics/v3/data/ga?ids=ga:123455&dimensions=ga:eventCategory,ga:eventAction,ga:eventLabel&metrics=ga:visits,ga:pageviews&start-date=2013-01-01&end-date=2020-01-01
[2] => Array
(
[start-date] => 2013-01-01
[end-date] => 2020-01-01
[ids] => ga:123455
[dimensions] => ga:eventCategory,ga:eventAction,ga:eventLabel
[metrics] => Array
(
[0] => ga:visits
[1] => ga:pageviews
)
[start-index] => 1
[max-results] => 1000
)
[3] => 1000
[4] => 9
There doesn't seem to be anything wrong with your code. Your code should be printing, what seems to me, the object ga:123455 if the code is executed. When printing this, this object will be converted to a string. PHP will do (string) ga:123455 (invoke the __toString() method on ga:123455) to convert an object to a string. If this method is absent, there must be a warning that ga:123455 cannot be converted to a string. __toString() might also return an empty string.
I would suggest debugging it by doing print var_dump( $jsonResponse[2]["ids"] ); and print var_dump( (string) $jsonResponse[2]["ids"] );.

php multi dimension array?

I am retrieving a multidimensional php array (I think) from an API, now all of the values return perfectly and when I dump the array with print_r I get this:
Event Object
(
[title] => test
[link] => google.com
[updated] => 2013-03-06T12:08:56.521-05:00
[id] => test
[name] => Copy of Copy of Copy of Mar 05, 2013 - TEST4
[description] =>
[registered] => 2
[createdDate] => 2013-03-06T12:08:56.521-05:00
[status] => COMPLETE
[eventType] => OTHER
[eventLocation] => EventLocation Object
(
[location] => test
[addr1] => test
[addr2] =>
[addr3] =>
[city] => madrid
[state] => andalucia
[country] =>
[postalCode] => 06103
)
[registrationUrl] => https://google.com
[startDate] => 2013-03-07T13:00:00-05:00
[endDate] => 2013-03-07T13:00:00-05:00
[publishDate] => 2013-03-06T12:11:15.958-05:00
[attendedCount] => 0
[cancelledCount] => 0
[eventFeeRequired] => FALSE
[currencyType] => USD
[paymentOptions] => Array
(
)
[registrationTypes] => Array
(
[0] => RegistrationType Object
(
[name] =>
[registrationLimit] =>
[registrationClosedManually] =>
[guestLimit] =>
[ticketing] =>
[eventFees] => Array
(
)
)
)
)
Now bumbling through wit my basic PHP i have found that i can list all of the first array items from [title] to [eventType] like this:
<?php
// get details for the first event returned
$Event = $ConstantContact->getEventDetails($events['events'][0]);
reset($Event);
while (list($key, $value) = each($Event)) {
echo "$key => $value \r\n<br/>";
}
?>
my question: All I need to do it retrieve [title] and [startDate] I don't need the rest now I could just hide the rest using Js and css but i am sure i am just being an idiot and there is an easier way to traverse this array so it only spits out the two values i need.
How do i do this?
You do not have to traverse the whole object. Just access the properties you want:
$title = $Event->title;
$startDate = $Event->startDate;
// or
echo $Event->title;
echo $Event->startDate;
It's actually an object - not an (associative) array!
What's the difference?
An object is an instance of a class. A class has methods and attributes (member variables).
Unlike C++ or some other OOP languages, you can define attributes dynamically without declaring them in the class declaration.
An array is simply a container for keys and their values.
It seems that it's not an array but an object so something like this:
echo $Event->title;
echo $Event->startDate;
Is it ...
<?php
// get details for the first event returned
$Event = $ConstantContact->getEventDetails($events['events'][0]);
reset($Event);
echo $Event->$title . "<br/>";
echo $Event->$startDate . "<br/>";
?>
? Or am I too simple?

JSON passing data to php for retrieve

(
[addF] => stdClass Object
(
[0] => stdClass Object
(
[productID] => 33
[fQty] => 11
[fPW] => 11
[fP] =>
[fH] => PVC
[fB] => SideBelt
[fP] => Single Pleat
[fPanelT] => stdClass Object
(
)
)
)
[addWP] => stdClass Object
(
)
[addRBC] => stdClass Object
(
)
[addRB] => stdClass Object
(
)
[addT] => stdClass Object
(
)
)
{"ErrorMessage":true}
The above output is base on the follow code below.
$arrOutput["ErrorMessage"]=print_r($objData);
I have use json to pass the array to PHP but i can't get the data.
i try to set the data but i have no value.
$ProductID=isset($objData->allData->addF[0]->productID) ? $objData->allData->addF[0]->productID : "123";
i tried to print_r will return true print will output 1
$objData->allData
it output 1
$objData->addF
also output 1
i don't understand y i can't set the value after i have decode it.
$objData=json_decode(stripslashes($Data));
Jquery part
allData.addF=addF;
allData.addWP=addWP;
allData.addRBC=addRBC;
allData.addRB=addRB;
allData.addT=addT;
//convert the data to json
var dataString = $.toJSON(allData);
$.post('test.php',"Data="+escape(dataString),function(data)
{
var obj=$.parseJSON(data);
alert(obj.ErrorMessage);
});
I need help to retrieve the data from it.
$ProductID=isset($objData->allData->addF->{"0"}->productID)

Categories