I want to loop through the MySQL results which is an array of Freebase MIDs and I want the output to be the names of the Freebase article!
Here's my code:
$query = "SELECT `mid` FROM `items`";
$result = mysql_query($query);
$count = 1;
while ($row = mysql_fetch_array($result)) {
$mid = $row['mid'];
$simple_query = array('name'=> null, 'mid'=>$mid);
$q_array = array('q'.$count=>array('query'=>$simple_query));
array_push ($query_array, $q_array );
$count++;
}
$jsonquerystr = json_encode($query_array);
$apiendpoint = "http://api.freebase.com/api/service/mqlread?queries";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$apiendpoint=$jsonquerystr");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$jsonresultstr = curl_exec($ch);
curl_close($ch);
$resultarray = json_decode($jsonresultstr, true); #true:give us the json struct as an array
foreach($resultarray as $name){
echo "$name<br>";
}
error:
{ "code": "/api/status/error", "messages": [ { "code": "/api/status/error", "message": "'list' object has no attribute 'get'" } ], "status": "500 Internal Error", "transaction_id": "cache;cache04.p01.sjc1:8101;2012-05-14T07:31:39Z;0079" }
Your $query_array should just be an associative array of queries by name rather than an array of associative arrays. So instead of this:
$q_array = array('q'.$count=>array('query'=>$simple_query));
array_push ($query_array, $q_array );
..it should look something like this:
$q_array = array('query'=>$simple_query);
$query_array['q'.$count] = $q_array;
However, that code is using the old Freebase API which is about to be deprecated. A better way to do this in the new API would be to structure it all as one query like this:
[{
"mid": null,
"name": null,
"topics:mid|=":[
"/m/045c7b",
"/m/0d6lp",
"/m/021ympy",
...
]
}]
This lets you pass in an array of MIDs and get back a name for each one. The URL to fetch this from the new API should look something like this:
https://www.googleapis.com/freebase/v1/mqlread/?query=[{...}]
Related
I am using curl_multi to send 2 post requests, the data is coming back as one $response correctly, I need to know the correct way to now handle this JSON data in PHP.
When I echo between <pre> tags my JSON is displayed correctly, however now I'm not sure how to take the data I want from it with PHP.
This is usually an easy task with a single API but I'm not sure why I'm having so much trouble with this here whilst using curl_multi!
json being returned inside my pre tags;
{
"Vehicles": [
{
"ExternalVehicleId": "9uq0jz1c",
"StockId": "1234",
"Errors": []
}
]
}
{
"Finance": [
{
"ExternalVehicleId": "9uq0jz1d",
"StockId": "4321",
"Errors": []
}
]
}
This is how the json comes back, but there are way more nested arrays. All appear to be in correct syntax wise.
And here's my php which I'm pretty sure is all fine;
$mh = curl_multi_init();
foreach ($urls as $key => $url) {
$chs[$key] = curl_init($url);
curl_setopt($chs[$key], CURLOPT_RETURNTRANSFER, true);
curl_setopt($chs[$key], CURLOPT_HEADER, false);
curl_setopt($chs[$key], CURLOPT_CONNECTTIMEOUT, 200);
curl_setopt($chs[$key], CURLOPT_TIMEOUT_MS, 25000);
curl_setopt($chs[$key], CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($chs[$key], CURLOPT_POST, true);
curl_setopt($chs[$key], CURLOPT_POSTFIELDS, json_encode($request_contents[$key]));
curl_setopt($chs[$key], CURLOPT_HTTPHEADER, $headers);
curl_multi_add_handle($mh, $chs[$key]);
}
$running = null;
do {
curl_multi_exec($mh, $running);
} while ($running);
foreach (array_keys($chs) as $key) {
$error = curl_error($chs[$key]);
$last_effective_URL = curl_getinfo($chs[$key], CURLINFO_EFFECTIVE_URL);
$time = curl_getinfo($chs[$key], CURLINFO_TOTAL_TIME);
$response = curl_multi_getcontent($chs[$key]); // get results
if (!empty($error)) {
echo "The request $key return a error: $error" . "\n";
} else {
echo "The request to '$last_effective_URL' returned '$response' in $time seconds." . "\n";
echo "<pre>";
echo $response;
echo "</pre>";
}
curl_multi_remove_handle($mh, $chs[$key]);
}
curl_multi_close($mh);
Join the responses into a single JSON array, which you can then json_decode():
$responses = [];
foreach (array_keys($chs) as $key) {
$responses[] = curl_multi_getcontent($chs[$key]);
}
$json = json_decode( '[' . join(',', $responses) . ']' );
var_dump($json);
You could unpack the response object with a foreach.
Something like
foreach($response as $value->$index){
echo “value ” . $value . “ index: ” . $index;
}
This is an example and should give you an idea how to debug your code.
I’m typing from a phone so I’m sorry
You may need to put a comma after closing the Vehicles brackets
{
"Vehicles": [
{
"ExternalVehicleId": "9uq0jz1c",
"StockId": "1234",
"Errors": []
}
]
}
,
{
"Finance": [
{
"ExternalVehicleId": "9uq0jz1d",
"StockId": "4321",
"Errors": []
}
]
}
I am trying to perform a GET request. The data is in the format as follows:
key=STRING (5 letters upper and lowercase)
num=INTEGER (2 digit number from 1-99)
{"data":"key=XXXXX, num=xx, key=XXXXX, num=xx"}
This is what I have so far:
<?php
$ch = curl_init('link_here');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
?>
Not sure how to sort the data and output values over 10 only.
Thanks
your question is not clear We need more information,
but if you have a long string like this
{"data":"key=str50, num=50, key=str01, num=1, key=str15, num=15, key=str08, num=8, key=str99, num=99"}
just decode Json and explode your array like this
$json = '{"data":"key=str50, num=50, key=str01, num=1, key=str15, num=15, key=str08, num=8, key=str99, num=99"}';
$encode = json_decode($json);
$data = $encode->data;
$explode = explode(",",$data);
$array = array();
for($i=0;$i<sizeof($explode);$i++){
if($i!=0)$i++;
$key = explode("=",$explode[$i]);
$val_next = explode("=",$explode[$i+1]);
if($val_next[1]>10)
$array[$key[1]] = $val_next[1];
}
asort($array);
print_r($array);
output is
Array ( [str15] => 15 [str50] => 50 [str99] => 99 )
I have below code & I am generating tracking_id values manually & its working fine :
<?php
$data = [
"client_reference_id" => "ABCD",
"tracking_id" => "1234",
];
$data = json_encode($data);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$curl_response = curl_exec($curl);
curl_close($curl);
echo $curl_response ."\n";
Result :
{"response":[{"tracking_id":"1234",}],
Now i need to create tracking_id dynamically.... so i tried like below :
"tracking_id" => "$r = 'DOCC'. mt_rand(0000000001,9999999999); echo $r;",
I got below Result :
{"response":[{"tracking_id":" = 'DOCC'. mt_rand(0000000001,9999999999); echo ;","
But i should get some random number as tracking_id....
Means php code inside parameter is not working....
As your require 10 digit random number:
function randomNumber($length) {
$result = '';
for($i = 0; $i < $length; $i++) {
$result .= mt_rand(1, 9);
}
return $result;
}
$data = [
"client_reference_id" => "ABCD",
"tracking_id" => 'DOCC'.randomNumber(10);//no need to echo, just assign it
];
$data = json_encode($data);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$curl_response = curl_exec($curl);
curl_close($curl);
echo $curl_response ."\n";
Refactor your code:
$r = 'DOCC'. mt_rand(0000000001,9999999999);
$data = [
"client_reference_id" => "ABCD",
"tracking_id" => $r,
];
Just replace $data array with the following.
$data = [
"client_reference_id" => "ABCD",
"tracking_id" => 'DOCC'. mt_rand(0000000001,9999999999),
];
We can convert php code how to json format?
I may have not accurately PHP coding I am beginner to learn about it because I'm new . I'll integrated into Android application.
I also draw pictures about how the information ?
for example, I want to do something like this: http://mikepenz.com/android/unsplash/pictures
<?php
// don't forget to change 'username' to your actual tumblr name
$request = 'http://walltumbler.tumblr.com/api/read/json';
$ci = curl_init($request);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
$input = curl_exec($ci);
// Tumblr JSON doesn't come in standard form, some str replace needed
$input = str_replace('var tumblr_api_read = ','',$input);
$input = str_replace(';','',$input);
// parameter 'true' is necessary for output as PHP array
$value = json_decode($input, true);
$content = $value['posts'];
// the number of items you want to display
$item = 98988;
// Tumblr provides various photo size, this case will choose the 75x75 square one
$type = 'photo-url-1280';
?>
{
"limit": null,
"offset": 0,
"count": 2442,
"total": 2442,
"data": [
<?php
for ($i=0;$i<=$item;$i++) {
if ($content[$i]['type'] == 'photo') {
echo '
{
"id": '.$i.';
"author": "Paul Jarvis",
"image_src": "' . $content[$i][$type] . '",
"color": "#7F7873",
"date": "2015-01-21 19:20:00",
"modified_date": "2014-09-01 22:36:53",
"width": 2500,
"height": 1667,
"ratio": 1.4997000694275,
"featured": 1,
"temp_id": 1
}';
$string = rtrim($item, ', ');
}
}
?>
]}
Try using the json_encode() function
<?php
$request = 'http://walltumbler.tumblr.com/api/read/json';
$ci = curl_init($request);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
$input = curl_exec($ci);
$input = str_replace('var tumblr_api_read = ','',$input);
$input = str_replace(';','',$input);
$value = json_decode($input, true);
$content = $value['posts'];
$item = 98988;
$type = 'photo-url-1280';
$photos_array = array();
for ($i=0;$i<=$item;$i++) {
if ($content[$i]['type'] == 'photo') {
$photos_array[] = array(
'id' => $i,
'author' => 'Paul Jarvis',
// Continue with all your values...
);
}
}
$json_data = array(
'limit' => null,
'offset' => 0,
'count' => 2442,
'total' => 2442,
'data' => $photos_array
);
// Then use json_encode to get your json data...
echo json_encode( $json_data );
Hope it helps
I have a JSON-response from embed.ly which I get in my PHP-script like this:
// jSON URL which should be requested
$json_url = 'http://api.embed.ly/1/oembed?key=hidden&url='.$_POST['url'];
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting jSON result string
My problem is that I want the responses from embed.ly embedded in my responsive layout, but embed.ly-responses of videos include with & height attributes:
{"provider_url": "http://www.youtube.com/", "description": "Markus Eisenrings Stromboli electric car on swiss television broadcast. See www.stromboli.ch for more information.", "title": "Stromboli Electric Car", "url": "http://www.youtube.com/watch?v=TJCZnpHuFS8", "author_name": "hangflug", "height": 360, "thumbnail_width": 480, "width": 640, "html": "<iframe width=\"640\" height=\"360\" src=\"http://www.youtube.com/embed/TJCZnpHuFS8?feature=oembed\" frameborder=\"0\" allowfullscreen></iframe>", "author_url": "http://www.youtube.com/user/hangflug", "version": "1.0", "provider_name": "YouTube", "thumbnail_url": "http://i1.ytimg.com/vi/TJCZnpHuFS8/hqdefault.jpg", "type": "video", "thumbnail_height": 360}
I tried removing all width & height-attributes from that JSON-string like this:
$result = json_encode(preg_replace('/\<(.*?)(width="(.*?)")(.*?)(height="(.*?)")(.*?)\>/i', '<$1$4$7>', json_decode($result)));
However, this is giving me a PHP-error.
Catchable fatal error: Object of class stdClass could not be converted to string in /Applications/XAMPP/xamppfiles/htdocs/projectname/ajax.php on line 22
Any ideas?
Can't you just do this:
$arr = json_decode($result, true);
unset($arr["height"], $arr["width"]);
$result = json_encode($arr);
UPDATE: For your specific example:
$arr = json_decode($result, true);
unset($arr["height"], $arr["width"]);
$arr_temp = explode(' ', $arr["html"]);
foreach ($arr_temp as $i => $val) {
if ((substr($val, 0, 7) != "height=") && (substr($val, 0, 6) != "width="))
$arr_html[] = $val;
}
$arr["html"] = implode(' ', $arr_html);
$json_result = json_encode($arr);
PHP Sandbox
finally got it to work with help form here like this:
$arr = json_decode($result, true);
foreach ($arr as $key => & $val) {
if($key=='html'){
$html = preg_replace('/\<(.*?)(width="(.*?)")(.*?)(height="(.*?)")(.*?)\>/i','<$1$4$7>', $arr['html']);
$arr[$key] = $html;
}
}
$result = json_encode($arr);