read JSON to PHP from javascript
I have an API that is available only in javascript (no PHP). It fetches some data of which I made a JSON string. What I need to know is how do I read this string in other page?
I tried using following :
$json = file_get_contents($url);
but of course the string I get is not JSON but is actually the javascript code that will generate json in original page. Any suggestions ? Thank you.
P.S. I also tried set cookie + redirect. Though that worked, I'd like to know a better solution.
Here is the javascript code
function searchComplete() {
if (imageSearch.results && imageSearch.results.length > 0)
{
var contentDiv = document.getElementById('content');
contentDiv.innerHTML = '';
var results = imageSearch.results;
var data = "{['data' : [\n";
for (var i = 0; i < results.length; i++) {
//var result = results[i];
var result = results[i];
data += "{\n";
data += "'url' : '"+result.url+"'";
data += "\n},\n";
}
data += "]]}";
setCookie("datajson", data, 1); // This is how i set the cookie and redirected
window.location = "JSPHP.php?data="+data;
开发者_运维技巧 document.getElementById('body').innerHTML = data;
}
}
PHP have great module for it:
json_encode
json_decode
Ok, you said it is not JSON. Thus json_decode() function is useless here without additional things. If this happens on browser side, you should probably pass the data to the server using AJAX.
Alternatively you can take a look how this API works (maybe it connects with some server using JSONs to exchange data?) and do the same in PHP.
EDIT:
You do not need to create a string of JSON on JavaScript side. JSON is itself object notation in JavaScript.
If you need to pass the data, just do something similar to this:
var data = [];
for (var i=0; i<results.length; i++){
data[] = {
'url': result.url
};
}
Then you only need to pass this data to the server. You can use .get() function (if you need to pass it using GET) from jQuery like that:
jQuery.get('http://example.com/', data, function(){
// something to do when successful
});
It is pretty simple and the basic is: create data correctly and pass it to the server using AJAX call.
Make yourself a web page that executes the javascript and saves the JSON result. Then post the JSON data to a PHP script (via XmlHttpRequest or regular form POST). Now your PHP code has access to the JSON data, and you can use json_decode
to access it.
精彩评论