Export sql to xml with utf8 encoding - sql

I try to find a solution by extracting sql table values in utf8 encoding but no luck.
The bellow code exports a right XML file named "test.xml" but without encoding.
Any suggestions?
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "admin";
$dbname = "My_DB";
mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbname);
$sql = "SELECT product_id, model, image FROM product";
$q = mysql_query($sql)or die(mysql_error());
$xml = "<products>";
while($r = mysql_fetch_array($q)){
$xml .= "<product>";
$xml .= "<id>";
$xml .= "<![CDATA[".$r["product_id"]."]]>";
$xml .= "</id>";
$xml .= "<name><![CDATA[" . $r["model"] . "]]></name>";
$xml .= "<image>".$r['image']."</image>";
$xml .= "</product>";
}
$xml .= "</products>";
$sxe = new SimpleXMLElement($xml);
$sxe->asXML("test.xml");
?>

What you are doing here is adding all data in a variable and then just outputting it to a file. Why don't you try formatting your XML file as you want it (instead of using SimpleXMLElement only in the end? What I mean is something like this:
[...]
$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
$xml .= "<products>";
while($r = mysql_fetch_array($q)){
$xml .= "<product>";
$xml .= "<id>";
$xml .= "<![CDATA[".$r["product_id"]."]]>";
$xml .= "</id>";
$xml .= "<name><![CDATA[" . $r["model"] . "]]></name>";
$xml .= "<image>".$r['image']."</image>";
$xml .= "</product>";
}
$xml .= "</products>";
echo $xml;
This will result to an XML file created on your own. Just saying because you are not using the SimpleXMLElement all the way, instead you are adding the XML elements and attributes manually. You can take a look at here to see how else you could have built your file!
Hope it helps!

Related

Hello am trying to make an API post request using php curl error code 32601

am new in api trying to see if my Api works once I execute the code am geting Error code 32601 'Method not found' I have gone through the code and though am not sure I think the error is syntax related any guidance will be appreciated
<?php
$key = '';
$secret = '';
$path = 'https://api.cloudtrax.com/voucher/network_id=254281';
$data = array(
"code"=> "b3c34test",
"duration"=> 1,
"max_users"=> 1,
"up_limit"=> 10,
"down_limit"=> 20,
"comment"=> "Free access for guests",
"purge_days"=> 2);
$headers = array(
'nonce' => 'ThisIsANonce',
'authorization' => "key=" . $key . ",timestamp=" . time() . ",nonce=" . $nonce,
'authorization_header' => "Authorization: " . $authorization,
'signature' => hash_hmac('sha256', $authorization . $path . $data, $secret),
);
$ch = curl_init($path);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
if ($result == FALSE) {
if (curl_errno($ch) == 0)
echo "#### NOTE ####: nil HTTP return: This API call appears to be broken" . "\n";
else
throw new Exception(curl_error($ch), curl_errno($ch)); }
else
echo "RESULT: \n" . $result . "\n";
?>

display dynamic data in multiple columns

I use an html string in php to display sql query results in a single column:
How can I use multiple columns to lay it out like this:
while($row = mysqli_fetch_array($q)){
$id = $row['id'];
$title = $row['title'];
$desc = $row['description'];
$link = $row['link'];
$output .= '<a href="' . $link . '">
<h3>' . $title . '</h3>
<p>' . $desc . '</p>
</a>';
}
Credit to hungrykoala for help on this one
$i = 0 ;
$resultsPerRow = 2 ;
$output = '<tr>';
while($row = mysqli_fetch_array($q)){
$i++;
$id = $row['id'];
$title = $row['title'];
$desc = $row['description'];
$link = $row['link'];
$output .= '<td>' .$title. '<br>' .$desc. '</td>';
if ($i % $resultsPerRow == 0) {
$output .= '</tr><td><br></td><tr>';
}
}
echo($output);
Then output to a table tag

Display data with same table but different condition sql

I have this kind of result, absent to Current wolcha was ok but i want to get the previous status of wolcha by getting or displaying only the total previous wolcha no need for the absent, lates etc. just the total.
I have this kind of result, absent to Current wolcha was ok but i want to get the previous status of wolcha by getting or displaying only the total previous wolcha no need for the absent, lates etc. just the total.
function getwolchastatus($salon_id){
global $db;
$query = "SELECT employee_attendance.emp_id,
employee_attendance.date,
employee_attendance.branch_id,
employee_attendance.user_id,
employee_profile.emp_no,
COUNT(IF(employee_attendance.status='A',1, NULL)) 'absent',
COUNT(IF(employee_attendance.status='L',1, NULL)) 'late',
COUNT(IF(employee_attendance.status='SL',1, NULL)) 'sick_leave',
COUNT(IF(employee_attendance.status='LWP',1, NULL)) 'leave_w_pay',
COUNT(IF(employee_attendance.status='LWOP',1, NULL)) 'leave_wo_pay',
COUNT(IF(employee_attendance.status='HD',1, NULL)) 'halfday'
FROM employee_attendance
INNER JOIN employee_profile ON employee_profile.emp_id = employee_attendance.emp_id
INNER JOIN users ON users.user_id = employee_profile.user_id WHERE MONTH(employee_attendance.date) = MONTH(CURRENT_DATE) AND YEAR(employee_attendance.date) = YEAR(CURRENT_DATE) AND users.status = 'activate' AND users.salon_id = 2 GROUP BY employee_attendance.emp_id";
$result = $db->query($query) or die($db->error);
$content = '';
while($row = $result->fetch_array()) {
extract($row);
setlocale(LC_MONETARY, 'en_PH');
$query2 = "SELECT employee_attendance.emp_id,
employee_attendance.date,
employee_attendance.branch_id,
employee_attendance.user_id,
employee_profile.emp_no,
COUNT(IF(employee_attendance.status='A',1, NULL)) 'absent2',
COUNT(IF(employee_attendance.status='L',1, NULL)) 'late2',
COUNT(IF(employee_attendance.status='SL',1, NULL)) 'sick_leave2',
COUNT(IF(employee_attendance.status='LWP',1, NULL)) 'leave_w_pay2',
COUNT(IF(employee_attendance.status='LWOP',1, NULL)) 'leave_wo_pay2',
COUNT(IF(employee_attendance.status='HD',1, NULL)) 'halfday2'
FROM employee_attendance
INNER JOIN employee_profile ON employee_profile.emp_id = employee_attendance.emp_id
INNER JOIN users ON users.user_id = employee_profile.user_id WHERE employee_attendance.date between '2017-12-01' and '2017-12-31' AND users.status = 'activate' AND users.salon_id = 2 GROUP BY employee_attendance.emp_id";
$result2 = $db->query($query2) or die($db->error);
$row2 = $result2->fetch_array();
$new_branch = new Branch;
$employee = new Employee;
$new_user = new Users;
$branch_name = $new_branch->get_branch_info($row['branch_id'], 'branch_name');
$first_name = $employee->get_employee_info($row['emp_id'], 'first_name');
$last_name = $employee->get_employee_info($row['emp_id'], 'last_name');
$nickname = $employee->get_employee_info($row['emp_id'], 'nickname');
$employee_name = $nickname;
//$today = date('MONTH');
// $date1 = DATEADD('DAY', -30, GETDATE());
if(($row['absent'] <3) && ($row['late'] < 2) &&($row['sick_leave'] < 1) && ($row['leave_w_pay'] < 1) && ($row['leave_wo_pay'] < 1) && ($row['halfday'] <2)){
$row['total'] = 1;
}else{
$row['total'] = 0;
}
if(($row2['absent2'] <3) && ($row2['late2'] < 2) &&($row2['sick_leave2'] < 1) && ($row2['leave_w_pay2'] < 1) && ($row2['leave_wo_pay2'] < 1) && ($row2['halfday2'] <2)){
$row2['total2'] = 1;
}else{
$row2['total2'] = 0;
}
$total3 = $row['total'] + $row2['total2'];
$content .= "<tr>";
// $content .= "<td>";
// $content .= $branch_name;
// $content .= "</td>";
$content .= "<td>";
$content .= $last_name.' '.$first_name;
$content .= "</td>";
$content .= "<td>";
$content .= $row['absent'];
$content .= "</td>";
$content .= "<td>";
$content .= $row['late'];
$content .= "</td>";
$content .= "<td>";
$content .= $row['sick_leave'];
$content .= "</td>";
$content .= "<td>";
$content .= $row['leave_w_pay'];
$content .= "</td>";
$content .= "<td>";
$content .= $row['leave_wo_pay'];
$content .= "</td>";
$content .= "<td>";
$content .= $row['halfday'];
$content .= "</td>";
$content .= "<td>";
$content .= $row['total'];
$content .= "</td>";
$content .= "<td>";
$content .= $row2['total2'];
$content .= "</td>";
$content .= "<td>";
$content .= $total3;
$content .= "</td>";
$content .= "</tr>";
}
echo $content;
}

FatSecret API - food.get method invalid signature

Hi I am new to FatSecret Platform API and i developed a PHP script to access food details using foods.search method Here is the foods.search method Api call example,used Curl and works perfect. <?php $consumer_key = "xxxxxxx"; $secret_key = "xxxxxxx"; //Signature Base String //<HTTP Method>&<Request URL>&<Normalized Parameters> $base = rawurlencode("GET")."&"; $base .= "http%3A%2F%2Fplatform.fatsecret.com%2Frest%2Fserver. api&"; //sort params by abc....necessary to build a correct unique signature $params = "method=foods.search&"; $params .= "oauth_consumer_key=$consumer_key&"; // ur consumer key $params .= "oauth_nonce=123&"; $params .= "oauth_signature_method=HMAC-SHA1&"; $params .= "oauth_timestamp=".time()."&"; $params .= "oauth_version=1.0&"; $params .= "search_expression=".urlencode($_GET['pasVar']); $params2 = rawurlencode($params); $base .= $params2; //encrypt it! $sig= base64_encode(hash_hmac('sha1', $base, "$secret_key&", true)); // replace xxx with Consumer Secret //now get the search results and write them down $url = "http://platform.fatsecret.com/rest/server.api?". $params."&oauth_signature=".rawurlencode($sig); //$food_feed = file_get_contents($url); list($output,$error,$info) = loadFoods($url); echo '<pre>'; if($error == 0){ if($info['http_code'] == '200') echo $output; else die('Status INFO : '.$info['http_code']); } else die('Status ERROR : '.$error); function loadFoods($url) { // create curl resource $ch = curl_init(); // set url curl_setopt($ch, CURLOPT_URL, $url); //return the transfer as a string curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // $output contains the output string $output = curl_exec($ch); $error = curl_error($ch); $info = curl_getinfo($ch); // close curl resource to free up system resources curl_close($ch); return array($output,$error,$info); } ?> the above script working perfect and retrieves food details using search method.But when i use food.get method to retrieve data using food_id it says invalid signature error,Here's the food.get method api call example,I have given correct keys and passed food_id parameter.Can someone help me to solve the issue,I am really struck on this code.It says invalid signature error. <?php $consumer_key = "xxxxxxxxx"; $secret_key = "xxxxxxxxxx"; //Signature Base String //<HTTP Method>&<Request URL>&<Normalized Parameters> $base = rawurlencode("GET")."&"; $base .= "http%3A%2F%2Fplatform.fatsecret.com%2Frest%2Fserver.api&"; //sort params by abc....necessary to build a correct unique signature $params = "method=food.get&"; $params .= "oauth_consumer_key=$consumer_key&"; // ur consumer key $params .= "oauth_nonce=".rand()."&"; $params .= "oauth_signature_method=HMAC-SHA1&"; $params .= "oauth_timestamp=".time()."&"; $params .= "oauth_version=1.0&"; $params .= "food_id=".urlencode($_GET['pasVar']); $params2 = rawurlencode($params); $base .= $params2; //encrypt it! $sig= base64_encode(hash_hmac('sha1', $base, "$secret_key&", true)); // replace xxx with Consumer Secret //now get the search results and write them down $url = "http://platform.fatsecret.com/rest/server.api?". $params."&oauth_signature=".rawurlencode($sig); //$food_feed = file_get_contents($url); list($output,$error,$info) = loadFoods($url); echo '<pre>'; if($error == 0){ if($info['http_code'] == '200') echo $output; else die('Status INFO : '.$info['http_code']); } else die('Status ERROR : '.$error); function loadFoods($url) { // create curl resource $ch = curl_init(); // set url curl_setopt($ch, CURLOPT_URL, $url); //return the transfer as a string curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // $output contains the output string $output = curl_exec($ch); $error = curl_error($ch); $info = curl_getinfo($ch); // close curl resource to free up system resources curl_close($ch); return array($output,$error,$info); } ?> Help me what's the error in the code and help me to solve the issue as i have to use this API in my project Thanks waiting for your replies....
You should order you params by alpha.
So you should do it in this order:
$params = "food_id=".urlencode($_GET['pasVar'])."&";
$params .= "method=food.get&";
$params .= "oauth_consumer_key=$consumer_key&"; // ur consumer key
$params .= "oauth_nonce=".rand()."&";
$params .= "oauth_signature_method=HMAC-SHA1&";
$params .= "oauth_timestamp=".time()."&";
$params .= "oauth_version=1.0";

cURL - Open files outside server's root directory

I am wondering, how can I access a file outside the root directory of my server?
For example, /home/username/FILE.mp3
The code i am currently using to open a file is the following:
<?php
$location = "ABSOLUTE-PATH/FILE.mp3";
$ch = curl_init($location);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FILETIME, true);
$data = curl_exec($ch);
$timestamp = curl_getinfo($ch, CURLINFO_FILETIME);
curl_close($ch);
if ($data === false) {
echo 'CURL Failed';
exit;
}
//Get file size
if (preg_match('/Content-Length: (\d+)/', $data, $matches)) {
$contentLength = (int)$matches[1];
}
$begin = 0;
$end = $contentLength - 1;
if (preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches))
{
$begin = intval($matches[1]);
if (!empty($matches[2]))
{
$end = intval($matches[2]);
}
}
if (isset($_SERVER['HTTP_RANGE']))
{ header('HTTP/1.1 206 Partial Content'); }
else
{ header('HTTP/1.1 200 OK'); }
header('Accept-Ranges: bytes');
header('Content-Length: ' . $contentLength);
header("Content-Range: bytes $begin-$end/$contentLength");
header('Content-Type: audio/mpeg');
header('Cache-Control: public, must-revalidate, max-age=0');
if ($timestamp != -1) { //otherwise unknown
header("Last-Modified: " . gmdate("D, d M Y H:i:s", $timestamp) . " GMT");
}
ob_clean();
flush();
echo ($data);
exit;
?>
I know as a fact that cURL doesn't work with relative paths and i assume that a file outside the root directory is treated as a relative link.
Why would you use cURL? Typically cURL would be something you would use to communicate with a different server via HTTP. Why not use file, file_get_contents, fopen or similar?