I am an old Greek Pharmacist and my hobby is web development.
So, I have this url
https://clinicaltrials.gov/api/query/study_fields?expr=lansoprazole&fields=NCTId%2CBriefTitle%2CCondition&min_rnk=1&max_rnk=10&fmt=json
and I want to have all its Json data in an html table.
I tried with Fetch Api, but I did not succeed :(
How can this be done with JavaScript or PHP?
Thank you in advance!
<?php
$jsondump = file_get_contents('https://clinicaltrials.gov/api/query/study_fields?expr=lansoprazole&fields=NCTId%2CBriefTitle%2CCondition&min_rnk=1&max_rnk=50&fmt=json');
// Decode JSON data to PHP associative array
$data = json_decode($jsondump, true);
if($data['StudyFieldsResponse']['MaxRank'] <= $data['StudyFieldsResponse']['NStudiesFound'])
{
$keynum=$data['StudyFieldsResponse']['MaxRank'];
}
else
{
$keynum=$data['StudyFieldsResponse']['NStudiesFound'];
}
echo ("NStudiesReturned: ") . $keynum;
echo "<hr><br>";
?>
<table border=1 width=800>
<tr><td>Rank</td><td>NCTId</td><td>BriefTitle</td><td>Condition</td></tr>
<?php
$x=0;
while ($x <= $keynum-1){
$rank = $data['StudyFieldsResponse']['StudyFields'][$x]['Rank'];
$nctid=$data['StudyFieldsResponse']['StudyFields'][$x]['NCTId'][0];
$title = $data['StudyFieldsResponse']['StudyFields'][$x]['BriefTitle'][0];
$condition_count=count($data['StudyFieldsResponse']['StudyFields'][$x]['Condition']);
//echo $condition_count;
echo "<tr><td> $rank</td><td>$nctid</td><td>$title</td><td><b>";
$ccx=0;
while ($ccx <= $condition_count-1){
$condition = $data['StudyFieldsResponse']['StudyFields'][$x]['Condition'][$ccx];
echo "<p>$condition</p>";
$ccx++;
}
echo "</b></td></tr>";
$x++;
}
?>
</table>
Related
My url type is like "http://localhost/boardgame/profile/Duncan/" the last word is the user name...
I just try to get some data from database and I need a user name to do this. I tried to get it from page URL but it doesn't work. Where did I go wrong? What has to be done? I'll be greateful if anybody can help...
<?php
$actual_link = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
//echo $actual_link;
$rest = substr($actual_link, 35, -1);
echo $rest;
$link = mysqli_connect("localhost", "root", "", "bgt");
if (mysqli_connect_error()) {
die ("Veritabanı bağlantısında hata var");
} if (($rest) !="") {
if (get_current_user_id($link) == '0') {
echo "<p>Kullanıcının koleksiyonunu görebilmek için giriş yapmanız
gerekiyor.</p>";
} else {
$query = "SELECT TITLE FROM wp_user_collections WHERE `user_name` =
'".mysqli_real_escape_string($link, $rest)."'";
echo "<div><h1>'".mysqli_real_escape_string($link, $rest)."'in
Koleksiyonu</h1><div>";
if($result = mysqli_query($link, $query)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>Oyun Adı</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>'" . $row['TITLE'] . "'</td>";
echo "</tr>";
}
echo "</table></div>";
}
}
}
} else {
echo "Kullanıcının koleksiyonunu görebilmek için <a
href='http://localhost/boardgame/profile/'".mysqli_real_escape_string($link,
$rest)."'>tıklayınız</a>";
}
?>
Here is the solution I have thought...using array then extracting the last element (or second last since there is a trailing '/' slash which is a delimiter)
$uri="http://localhost/boardgame/profile/Duncan/";
$uriParts=explode('/', $uri); //converts the uri string into an array of words separated by forward slash
$name=$uriParts[sizeOf($uriParts)-1-1]; //the user name comes from 2nd last item as the last item is empty
echo $name;
I could suggest you use Regular Expression to extract the user name, however I'm not well versed with it yet.
I have to read a txt file into a HTML table.
There are many fields in it but I only want to read the field that says "value".
Here is my txt file:
one=availability:, timestamp=90754, value=no
two=description:, timestamp=074693, value=not sure
three=Name, timestamp=90761, value=yes
The one, two, three values are my row headers and I want it to display the values underneath.
Is there anyway of doing this using iframe?? PHP is not working for me.
Supposing the value is always the last field and you are reading the file line by line I would use a dirty approach:
$value = explode('value=', $line)[1];
longwinded approach
$headers=[];
$values=[];
$lines = file('./homework.txt', FILE_IGNORE_NEW_LINES);
foreach($lines as $line){
$chunks = explode(',',$line);
foreach($chunks as $index => $chunk){
list($key, $value) = explode('=', trim($chunk));
if(!$index){
$headers[] = $value;
}
if('value' === $key){
$values[] = $value;
}
}
}
echo "<table><thead><tr>";
foreach($headers as $h){
echo "<th>{$h}</th>";
}
echo "</tr></thead><tbody><tr>";
foreach($values as $v){
echo "<td>{$v}</td>";
}
echo "</tr></tbody></table>";
If all rows follow the same pattern you can probably use:
//$textfilestring = "one=availability:, timestamp=90754, value=no
//two=description:, timestamp=074693, value=not sure
//three=Name, timestamp=90761, value=yes";
$textfilestring = file_get_contents("PATH_TO_FILE");
$arraylines = explode("\n", $textfilestring);
for ($i=0;$i<count($arraylines);$i++) {
$arraylines[$i] = explode("value=", $arraylines[$i]);
}
echo "<pre>";
var_dump($arraylines);
echo "</pre>";
echo $arraylines[0][1] . "<br>";
echo $arraylines[1][1] . "<br>";
echo $arraylines[2][1] . "<br>";
$arraylines should be twodimensional with one part beeing
one=availability:, timestamp=90754,
and one beeing
no
Not tested though.
I am trying to extract specific values returned from google api
<?php
$url='http://maps.googleapis.com/maps/api/distancematrix/json?origins=19.1629924,72.83930190&destinations=19.1802370,72.8554149&sensor=false';
$contents = file_get_contents($url);
$contents = utf8_encode($contents);
$array=json_decode($contents);
echo $array['rows']['elements']['distance']['value'];
?>
I expected the value of 4238 to be returned. Instead I get an error:
`PHP Fatal error: Cannot use object of type stdClass as array in test9.php on` line 7
Te correct solution is:
echo $array->rows[0]->elements[0]->distance->value;
Do the following to see the json:
<?php
$url='http://maps.googleapis.com/maps/api/distancematrix/json?origins=19.1629924,72.83930190&destinations=19.1802370,72.8554149&sensor=false';
$contents = file_get_contents($url);
$contents = utf8_encode($contents);
echo "<pre>";
echo $contents;
echo "\n";
echo "\n";
$array=json_decode($contents);
echo $array->rows[0]->elements[0]->distance->value;
?>
http://www.json.org/
have you tried node.js?
The following code solved the problem:
$array=json_decode($contents, true);
echo $array['rows'][0]['elements'][0]['distance']['value'];
i have Yii code as-
public function actionpublishPollResult()
{
$model=new Polloption();
$json='{"pollId":2}';
$obj=json_decode($json);
$model->pollId=$obj->pollId;
$options=Polloption::model()->findAllByAttributes(array('pollId'=>$model->pollId));
$total=0;
foreach ($options as $option)
{
echo "option id :-".$option->optionId."<br>";
$vote=new Pollvote();
echo "Number of votes to option :".$option->optionId." "."is=".count($option->pollvotes)."</br>";
$total=$total+count($option->pollvotes);
$data[] =count($option->pollvotes);
}
echo "</br>";
echo "Total number of votes obtained=".$total;
foreach ($data as $votepercentage)
{
$percentageResult[]=$votepercentage/$total*100;
}
echo "</br>";
echo CJSON::encode(array('options'=>$options,'percentagevotes'=>$percentageResult));
}
So it is giving me output as
{"options":[{"optionId"=>1,"option"=>"abc"},{"optionId"=>2,"option"=>"xyz"}],{"percentagevotes":[25,75]}}
But i want to add this percentagevotes field in options array only. So what changes i need to make in above foreach structure. Because $total will obtain only after whole loop of options is executed.. So how to calculate and add percentagevotes field in foreach of options only. Please guide me...
Edit your second foreach loop as
$toJson=array();
foreach ($data as $i=>$votepercentage)
{
$tmp=array();
$tmp['optionId']=$option[$i]->optionId;
$tmp['option']=$option[$i]->option;
$tmp['percentageVote']=$votepercentage/$total*100;
$toJson[]=$tmp;
}
then
echo CJSON::encode(array('options'=>$toJson));
I want to convert my sql data to csv files while clicking on a button. The code fragments I found for sql to CSV conversion were in PHP, and I'm trying to convert it to CakePHP since I'm working in CakePHP.
Here is the PHP code I'm tring to convert:
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field']."; ";
$i++;
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j]."; ";
}
$csv_output .= "\n";
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
SOLUTION
Function in the Controller:
function exporttocsv()
{
$this->set('headers',$this->Result->find('all',array('fields'=>'Result.label')));
$this->set('values',$this->Result->find('all',array('fields'=>'Result.value')));
}
exporttocsv.ctp file:
<?php
foreach($headers as $header):
$csv_output .=$header['Result']['label'].", ";
endforeach;
$csv_output .="\n";
if(!empty($values)){
foreach($values as $value):
$csv_output .=$value['Result']['value'].", ";
endforeach;
$csv_output .="\n";
}
else{
echo "There is no data to export.";
}
$filename = "export_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
?>
First of all, you don't do queries and output in the same file in Cake. You query the data as usual in the Controller, $this->set() the result to the view, and in the view you do something like this:
foreach ($results as $result) {
echo join(', ', $result['COLUMNS']);
echo "\n";
}
Outputs something like this:
value, varchar(25), NO, , ,
submitter, int(11), NO, , ,
...
Since Cake automatically wraps a layout around your view, you'll have to set the layout to something different, like 'ajax' (which is simply an empty layout).
deceze is correct about outputting the results from the view file. You'll just need to set some headers so that it appears as a file download on the client side. You can simply put these 2 calls in the top of your view:
header("Content-type:application/vnd.ms-excel");
header("Content-disposition:attachment;filename=\"{$filename}\"" );
If you plan on doing csv downloads in more than one place in your application, I'd recommend this helper:
http://bakery.cakephp.org/articles/view/csv-helper-php5
I use it and it works well.