Mengekstrak JSONP Resultset dalam PHP
Panggil balik JSONP ialah kaedah biasa untuk mengembalikan data daripada API berasaskan JavaScript. Dalam keadaan ini, anda mempunyai satu titik akhir sedemikian yang mengembalikan kandungan JSONP berikut:
YAHOO.Finance.SymbolSuggest.ssCallback({"ResultSet":{"Query":"yahoo","Result":[{"symbol":"YHOO","name": "Yahoo! Inc.","exch": "NMS","type": "S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"YAHOY.PK","name": "YAHOO JAPAN CORP","exch": "PNK","type": "S","exchDisp":"Pink Sheets","typeDisp":"Equity"},{"symbol":"ETD","name": "Citigroup Inc. ELKS On Yahoo","exch": "PCX","type": "S","typeDisp":"Equity"},{"symbol":"YOJ.BE","name": "YAHOO JAPAN","exch": "BER","type": "S","exchDisp":"Berlin","typeDisp":"Equity"},{"symbol":"YHO.SG","name": "YAHOO","exch": "STU","type": "S","exchDisp":"Stuttgart","typeDisp":"Equity"},{"symbol":"YAHOF.PK","name": "YAHOO JAPAN CORP","exch": "PNK","type": "S","exchDisp":"Pink Sheets","typeDisp":"Equity"},{"symbol":"YHO.HM","name": "YAHOO","exch": "HAM","type": "S","exchDisp":"Hamburg","typeDisp":"Equity"},{"symbol":"YOJ.DE","name": "YAHOO JAPAN","exch": "GER","type": "S","exchDisp":"XETRA","typeDisp":"Equity"},{"symbol":"YHO.DU","name": "YAHOO","exch": "DUS","type": "S","exchDisp":"Dusseldorf Stock Exchange","typeDisp":"Equity"},{"symbol":"YHOO.BA","name": "YAHOO INC.","exch": "BUE","type": "S","exchDisp":"Buenos Aires","typeDisp":"Equity"}]}})
Untuk mengekstrak data JSON daripada kandungan ini, anda boleh menggunakan fungsi jsonp_decode():
<code class="php">function jsonp_decode($jsonp, $assoc = false) { // PHP 5.3 adds depth as third parameter to json_decode if($jsonp[0] !== '[' && $jsonp[0] !== '{') { // we have JSONP $jsonp = substr($jsonp, strpos($jsonp, '(')); } return json_decode(trim($jsonp,'();'), $assoc); }</code>
Dengan fungsi ini, anda boleh mengakses data JSON seperti berikut:
<code class="php">$data = jsonp_decode($response);</code>
Pembolehubah $data akan mengandungi objek dengan struktur berikut:
{ "ResultSet": { "Query": "yahoo", "Result": [ { "symbol": "YHOO", "name": "Yahoo! Inc.", "exch": "NMS", "type": "S", "exchDisp": "NASDAQ", "typeDisp": "Equity" }, // ... ] } }
Anda kemudian boleh mengakses titik data individu seperti yang diperlukan.
Atas ialah kandungan terperinci Bagaimanakah anda mengekstrak data JSON daripada panggilan balik JSONP dalam PHP?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!