I am trying to display coordinates from Twitter Search API 1.1 (GET).
I can output the entire JSON file after encoding the tweets - http://pastebin.com/bKLye2an
$search = str_replace("#", "%23", $search);
$tweets = $connection->get("https://api.twitter.com/1.1/search/tweets.json?q=".$search."&count=".$notweets);
$json = json_encode($tweets);
However, in PHP I used the following codes to display the coordinates and nothing appears.
foreach ($json['statuses'] as $key => $value)
{
foreach ($json['coordinates']['coordinates'] as $key => $value)
{
echo "$key: $value\n";
};
};
As far as I can see, the structure is statuses-coordinates-coordinates for geo.
How do I echo coordinates (if present) for all tweets in search).
Given your sample json string, a simple foreach is enough. Consider this example:
$json_string = '{"statuses":[{"metadata":{"result_type":"recent","iso_language_code":"en"},"created_at":"Mon Jun 16 08:35:18 +0000 2014","id":478455763761786880,"id_str":"478455763761786880","text":"Later go shop at cold storage. LOLOL","source":"Twitter for Android<\/a>","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":559622523,"id_str":"559622523","name":"AhYong","screen_name":"likeasomebodeh","location":"To each and every road.","description":"Fun-Sized \/ CE1404N \/ BARVENGERS \/ Sagittarian \/ Sixth Gun \/ Drummer - Wannabe","url":"http:\/\/t.co\/PFSXy17655","entities":{"url":{"urls":[{"url":"http:\/\/t.co\/PFSXy17655","expanded_url":"http:\/\/ask.fm\/Ah_Yong","display_url":"ask.fm\/Ah_Yong","indices":[0,22]}]},"description":{"urls":[]}},"protected":false,"followers_count":329,"friends_count":444,"listed_count":1,"created_at":"Sat Apr 21 13:30:49 +0000 2012","favourites_count":4930,"utc_offset":28800,"time_zone":"Beijing","geo_enabled":false,"verified":false,"statuses_count":33116,"lang":"en","contributors_enabled":false,"is_translator":false,"is_translation_enabled":false,"profile_background_color":"131516","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme14\/bg.gif","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme14\/bg.gif","profile_background_tile":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/459318345003593728\/mhjxKipm_normal.jpeg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/459318345003593728\/mhjxKipm_normal.jpeg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/559622523\/1401358655","profile_link_color":"009999","profile_sidebar_border_color":"EEEEEE","profile_sidebar_fill_color":"EFEFEF","profile_text_color":"333333","profile_use_background_image":true,"default_profile":false,"default_profile_image":false,"following":false,"follow_request_sent":false,"notifications":false},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[],"symbols":[],"urls":[],"user_mentions":[]},"favorited":false,"retweeted":false,"lang":"en"}],"search_metadata":{"completed_in":0.016,"max_id":478455763761786880,"max_id_str":"478455763761786880","next_results":"?max_id=478455763761786879&q=flu%20OR%20cold%20OR%20%23flu%20OR%20%23cold%20OR%20%23snot%20OR%20%23ill&count=1&include_entities=1","query":"flu+OR+cold+OR+%23flu+OR+%23cold+OR+%23snot+OR+%23ill","refresh_url":"?since_id=478455763761786880&q=flu%20OR%20cold%20OR%20%23flu%20OR%20%23cold%20OR%20%23snot%20OR%20%23ill&include_entities=1","count":1,"since_id":0,"since_id_str":"0"}}';
$json = json_decode($json_string, true);
foreach($json['statuses'] as $key => $json_values) {
if(isset($json_values['coordinates']) && !empty($json_values['coordinates'])) {
// continue your processes if key exists and not empty
}
}
Important Note: In your given json, take note, your coordinates is null
Related
I tried to set up app attestation between my app and php but I rarely find any other source of explaination than Apple's own documentation, which let me stuck quite at an early state. So far I got the following steps:
On the client side, following https://developer.apple.com/documentation/devicecheck/establishing_your_app_s_integrity, I creted my attestation as a base64 encoded string:
attestation.base64EncodedString()
I then send that string to the server, following https://developer.apple.com/documentation/devicecheck/validating_apps_that_connect_to_your_server from now on.
The documentation says, that the attestation is in the CBOR format. I therefor first decode the base64 encoded string and parse it using (https://github.com/Spomky-Labs/cbor-php).
<?php
use CBOR\Decoder;
use CBOR\OtherObject;
use CBOR\Tag;
use CBOR\StringStream;
$otherObjectManager = new OtherObject\OtherObjectManager();
$tagManager = new Tag\TagObjectManager();
$decoder = new Decoder($tagManager, $otherObjectManager);
$data = base64_decode(/* .. base64 encoded attestation string as send from the client (see swift snippet above) */);
$stream = new StringStream($data);
$object = $decoder->decode($stream);
$norm = $object->getNormalizedData();
$fmt = $norm['fmt'];
$x5c = $norm['attStmt']['x5c'];
From the documentation, the normalized object should have the following format:
{
fmt: 'apple-appattest',
attStmt: {
x5c: [
<Buffer 30 82 02 cc ... >,
<Buffer 30 82 02 36 ... >
],
receipt: <Buffer 30 80 06 09 ... >
},
authData: <Buffer 21 c9 9e 00 ... >
}
which it does:
$fmt == "apple-appattest" // true
Then the next according to the documentation is described as:
Verify that the x5c array contains the intermediate and leaf certificates for App Attest, starting from the credential certificate in the first data buffer in the array (credcert). Verify the validity of the certificates using Apple’s App Attest root certificate.
However, I don't know how to proceed further on this. The content of e.g. $norm['attStmt']['x5c'][0] is a mix of readable chars and glyphs. To give you an idea, this is a random substring from the content of $norm['attStmt']['x5c'][0]: "Certification Authority10U Apple Inc.10 UUS0Y0*�H�=*�H�=B��c�}�". That's why I'm not really sure wheather I have to perform any further encodeing/decoding steps.
I tried parsing the certificate but without any luck (both var_dump return false):
$cert = openssl_x509_read($x5c[0]);
var_dump($cert); // false - indicating that reading the cert failed
$parsedCert = openssl_x509_parse($cert, false);
var_dump($parsedCert); // false - of course, since the prior step did not succeed
Any ideas, guidance or alternative ressources are highly appreciated. Thank you!
After a while I came up with the following solution. The $x5c field contains a list of certificates, all in binary form. I wrote the folowing converter to create a ready-to-use certificate in PEM format, which does the following:
base64 encode the binary data
break lines after 64 bytes
add BEGIN and END markers (also note the trailing line-break on the end certificate line)
function makeCert($bindata) {
$beginpem = "-----BEGIN CERTIFICATE-----\n";
$endpem = "-----END CERTIFICATE-----\n";
$pem = $beginpem;
$cbenc = base64_encode($bindata);
for($i = 0; $i < strlen($cbenc); $i++) {
$pem .= $cbenc[$i];
if (($i + 1) % 64 == 0)
$pem .= "\n";
}
$pem .= "\n".$endpem;
return $pem;
}
the following then works:
openssl_x509_read(makeCert($x5c[0]))
Similar to this unsolved question
My PHP output requires JSON_NUMERIC_CHECK enabled, however there is one string nick column in my database that needs to be returned originally as a string. Values in that column can contain numbers and there's no length restriction. Code example:
$response["players"] = array();
...
$stmt = $connection->prepare('SELECT id, nick FROM players WHERE NOT id = ? ORDER BY nick');
$stmt->bind_param('i', $_POST["id"]);
$stmt->execute();
$result = $stmt->bind_result($id, $nick);
while ($stmt->fetch()) {
$players = array();
$players["id"] = $id;
$players["nick"] = $nick;
array_push($response["players"], $players);
}
...
echo json_encode($response, JSON_NUMERIC_CHECK);
For example, nick "007" is being returned as "7" and I need it to be the original "007". Removing "JSON_NUMERIC_CHECK" helps, but it bugs the rest of the code. Strval() function used like quoted below didn't help.
$result = $stmt->bind_result($id, strval($nick));
$players["nick"] = strval($nick);
In PHP there is unfortunately no explicit type for variables, this makes your problem not so easy to solve.
I came with 2 solution.
1) if you like OOP, make a Serializable, Arrayable class to use as container for your string with a method returning the right encoded value.
2) first encode using JSON_NUMERIC_CHECK in order to make sure your data is what you expect it is, then decode the validated data, manually set the string to its origina value, then encode again but this time not using JSON_NUMERIC_CHECK.
$str = $response['nick'];
$response = json_decode(json_encode( $response, JSON_NUMERIC_CHECK ) );
$response->nick = $str;
$response = json_encode( $response );
The management of numbers is strange to say the least ...
It's almost scary !
then on PHPTESTER:
$CUSTOMER['id'] = 123;
$CUSTOMER['tel'] = '06 06 06 06 06';
// unbug for zero top of tel number -> json_encode
$CUSTOMER['tel'] = "".$CUSTOMER['tel']."";
echo json_encode($CUSTOMER, JSON_NUMERIC_CHECK);
Output : {"id":123,"tel":"06 06 06 06 06"}
On my host (same code) : Output : {"id":123,"tel":"6 06 06 06 06"} // zero was removed !
I found an unlikely solution :
I surrounded the variable with a space ...
$CUSTOMER['tel'] = " ".$CUSTOMER['tel']." "; // wrap with spaces
Output (on my host) : {"id":123,"tel":"06 06 06 06 06"}
in PHP version 5.5
Here is a solution, I would like to have your opinion, in any case it worked for me.
how to convert HTML data to json, example as below, description content how to convert as json, it is from mysql, php., how to send json responce as plain text, but description comes from the mysql db as it is, but how to send the json responce api to androind.
public function actionTestanalysis()
{
//echo $keyword=$_POST['keyword'];
$query= Yii::app()->db->createCommand("select * from test ORDER BY id DESC")->queryAll();
$arr = array();
if(count($query) > 0) {
foreach($query as $query){
$arr[] = $query;
}
}
# JSON-encode the response
$json_response = json_encode($arr);
// # Return the response
echo $json_response;
//exit;
}
json responce
[
{
"id": "99",
"name": "Max-Gain on or before 25th January 2016 in Max India Limited.",
"description": "
\r\n\tMax India Limited has announced the Record date for Three way De-Merger as 28th January 2016 (Thursday). <\/div>\r\n
\r\n\t <\/div>\r\n
\r\n\tAnyone want to Gain from the three way De-Merger of Max India Group one should buy the shares of Max India Limited on or before – 25th January 2016 (Cum-Date – Monday Tentavily) otherwise to be on safer side you can buy on or before 22nd January 2016(Friday) and get invested in it.<\/div>\r\n
\r\n\t <\/div>\r\n
\r\n\tIf any investor invests for a period Of 12 – 18 Months , this scrip will be a Multifold - Multi Bagger.<\/div>\r\n
\r\n\t <\/div>\r\n
\r\n\tTo View the full report on Max India Limited authored . <\/div>\r\n
\r\n\t <\/div>\r\n
\r\n\tPlease Click The Below Link<\/div>\r\n
\r\n\t
\r\n\t\thttp:\/\/www.test.com\/index.php\/newsOpportunities\/list\/scroll\/no-pain-all-gain-maximum-benefit-in-max-india-ltd<\/a><\/p>\r\n<\/div>\r\n",
"image": "",
"status": "unlock"
},
You have also one error in the cycle in your code.
Try this:
if (count($query) > 0) {
foreach ($query as $queryElement) {
$el = $queryElement;
$el['description'] = trim(preg_replace('/\s+/', ' ', strip_tags($el['description'])));
$arr[] = $el;
}
}
Try before: echo $json_response set header content type to application/json
<?PHP
header('Content-Type: application/json');
echo $json_response;
Use htmlentities() instead of strip_tags(), in order to retain actual content stored in db.
Following is my code which I am using for testing purposes so far. I have to use it further in my project.
It access a certain web service and retrieves data as xml. XML is brought to $arr array.
Address of $url and 3rd parameter in client->call() are not mentioned on purpose.
$url = "";
$client= new nusoap_client($url);
$param = array("status"=>"p2");
$arr = $client->call('getAllVisitByStatus',$param,'');
echo $arr."\n";
$size = sizeof($arr);
echo $size;
for($num=0; $num<986; ++$num)
{
echo $arr[$num], "\n";
if($arr[$num] == '>')
{
echo "<br/> ";
}
}
If I save the data returned by client->call() into an array and print it with a loop then it prints the XML like this
<?xml version = "1.0" encoding = "UTF - 8" standalone = "yes" ?>
<lists>
<visitW>
<followup> 2015 - 01 - 30 00:50:00.0 </followup>
<person_id> 12 </person_id>
<remarks> nothing </remarks>
<treatment> doing </treatment>
<visit_date> 2015 - 01 - 04 - 00 - 24 - </visit_date>
<visit_id> 4 </visit_id>
<visit_type> Hesschart</visit_type>
</visitW>
</lists>
However, if take $arr as a string, it prints this:
2015-01-30 00:50:00.0 12 nothing doing 2015-01-04-00-24- 4 Hesschart
So, in a string it prints without tags and like this.
The problem is that when the size of array is printed, it prints 1. However, the array contains the whole XML brought as a result of service call.
When I use a loop of exact number of elements i.e. 986, then it prints the whole XML as it is.
The question is that why does it show 1 as the size of the array? Also, can this array containing XML be put in DOM Parser?
I found this web service which provides the date time of a timezone. http://www.earthtools.org/timezone-1.1/24.0167/89.8667
I want to call it & get the values like isotime with php.
So I tried
$contents = simplexml_load_file("http://www.earthtools.org/timezone-1.1/24.0167/89.8667");
$xml = new DOMDocument();
$xml->loadXML( $contents );
AND also with
file_get_contents
With file_get_contents it gets only a string of numbers not the XML format. Something like this
1.0 24.0167 89.8667 6 F 20 Feb 2014 13:50:12 2014-02-20 13:50:12 +0600 2014-02-20 07:50:12 Unknown
Nothing worked. Can anyone please help me that how can I get the isotime or other values from that link using PHP?
Everything works):
$url = 'http://www.earthtools.org/timezone-1.1/24.0167/89.8667';
$nodes = array('localtime', 'isotime', 'utctime');
$cont = file_get_contents($url);
$node_values = array();
if ($cont && ($xml = simplexml_load_string($cont))) {
foreach ($nodes as $node) {
if ($xml->$node) $node_values[$node] = (string)$xml->$node;
}
}
print_r($node_values);