setlocale(LC_ALL, 'it_IT'); set, but still dates in english - php

I have this code which through json_decode retrieves my latest tweets, their date, etc.
<?php setlocale(LC_ALL, 'it_IT'); ?>
<?php include("twitter_auth.php");
echo "<ul style='color:#6E6E6E'>";
foreach ($twitter_data as $tweet)
{
if (!empty($tweet)) {
$text = $tweet->text;
$text_in_tooltip = str_replace('"', '', $text); // replace " to avoid conflicts with title="" opening tags
$id = $tweet->id;
$time = strftime('%d %B', strtotime($tweet->created_at));
$username = $tweet->user->name;
}
echo '<li><span title="'; echo $text_in_tooltip; echo '">'; echo $text . "</span><br>
<small>'; echo $time; echo '</small> -
<small>rispondi</small> -
<small>retweet</small> -
<small>preferito</small></li>';
}
echo '</ul>';
?>
Problem is that $time outputs something like "03 February" even though there is a setlocale(LC_ALL, 'it_IT');. What's the error? How can I have dates output in italian?
System: PHP 5.4.11 and nginx (on Ubuntu Server).
EDIT: I also ran dpkg-reconfigure locales:
Generating locales...
en_US.UTF-8... up-to-date
it_IT.UTF-8... up-to-date
Generation complete.

Silly as it may sound I solved changing the line to:
<?php setlocale(LC_ALL, 'it_IT.UTF-8'); ?>

Related

gettext is not giving result from .mo file, it is showing same as I am writing in echo

I am beginner and doing first time language translate for my web application.
kindly help me , where I am doing mistake, but I am not getting the result i'm expecting. I have installed gettex, I have changed in php.ini file for to remove extention(;), i have restarted many time the server, I creating .po file from poedit and mdifying evrytime the .mo file.
I don't know where I am wrong.
Please help..!
I would like to share the out put also, as I am printing many things for checking the right thing.
in my .po file I wrote:
# Test 1
msgid "This is moon"
msgstr "This is Sun"
So it must print "This is Sun", but its printing:
gettext working fine
Locale Language::de_DE
C:\xampp\htdocs\Test_project\Locale\de_DE\LC_MESSAGES
Path is Correct!!
C:\xampp\htdocs\Test_project\Locale\de_DE\LC_MESSAGES
This is moon
[result][1]
here is my code
if (function_exists("gettext")){
echo "gettext working fine";
}else{
echo "Extra stuff must be installed";
}
echo "<br>";
$language = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
echo "Locale Language::".$language;
echo "<br>";
putenv("LANG=". $language);
setlocale(LC_ALL, $language);
// set the text domain as "messages"
$domain = "messages";
$pathToDomain = 'C:\xampp\htdocs\Test_project\Locale\de_DE\LC_MESSAGES';
echo $pathToDomain;
echo "<br>";
if ($pathToDomain != bindtextdomain($domain, $pathToDomain)) {
// Error handling.
$hi = bindtextdomain($domain, $pathToDomain);
echo "hello".$hi;
echo "<br>";
echo "Path Incorrect";
}
else{
$hi = bindtextdomain($domain, $pathToDomain);
echo "Path is Correct!!";
echo "<br>";
echo $hi;
}
bindtextdomain($domain, $pathToDomain);
bind_textdomain_codeset($domain, 'UTF-8');
textdomain($domain);
echo "<br>";
echo gettext("This is moon");
$language = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
Will give you a locale string such as de_DE - however Windows won't accept that string, it would need to be something like deu_deu
You can test this with:
echo setlocale(LC_ALL, $language) ? "true" : "false";
There are two ways around this:
1) use setlocale(LC_ALL, 'deu_deu'); which may upset the live site
2) add putenv('LC_ALL=' . $language);
In a nutshell - when you strip your code right back, this should work on Windows:
$language = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
putenv('LANG=' . $language);
if(!defined('LC_ALL')) putenv('LC_ALL=' . $language);
setlocale(LC_ALL, $language);
$domain = 'messages';
$pathToDomain = 'C:\xampp\htdocs\Test_project\Locale';
bindtextdomain($domain, $pathToDomain);
bind_textdomain_codeset($domain, 'UTF-8');
textdomain($domain);
echo _("This is moon");

Remove text from string php

I have a table called 'filename'. I try to output <a> tags in a loop from it like this:
<?php
while($sermon = mysql_fetch_assoc($sermonsQ)) {
echo '<a href="admin/'. $sermon ['filename'] . '">';
echo 'download</a></td>';
}
Current problem is, that $sermon['filename'] containts a leading path like path/test.mp3. But I need only the filename without the path, like test.mp3. How can I do this?
Use basename() for that. It will return the filename without the leading path:
basename($sermon ['filename'])
You can use path_info()
<?php
$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');
echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // since PHP 5.2.0
?>
also mysql_* functions are depracated so you shouldn't use them for example to PDO or mysqli
<?php
while($sermon = mysql_fetch_assoc($sermonsQ)) {
$filename = explode('/',$sermon ['filename']);
echo '<a href="admin/'. $filename[1] . '">';
echo 'download</a></td>';
}

PHP gettext stopped working

I am on Ubuntu running Apache. The problem (not working) occurs on my production Strato webserver.
My PHP has gettext support, but it does not translate anything, although the strings are translated in the .mo file.
This is my code:
if (function_exists('bindtextdomain')) {
$domain = 'address_db';
echo putenv('LC_MESSAGES='.$lang);
echo '<br />';
echo setlocale(LC_MESSAGES, $lang);
echo '<br />';
$path = bindtextdomain($domain, "../locale/");
echo $path;
echo '<br />';
echo file_exists($path.'/'.$lang.'/LC_MESSAGES/'.$domain.'.mo') ? 'yes' : 'no';
echo '<br />';
echo bind_textdomain_codeset($domain, "iso-8859-1");
echo '<br />';
echo textdomain($domain);
echo '<br />';
$available_languages = array(
array('de_DE', _('German')),
array('en', _('English')),
array('nl', _('Dutch')),
array('tr', _('Turkish'))
);
echo _('Cancer');
}
The output is kind of promising:
1
/home/mu/Branches/address_db/locale
yes
iso-8859-1
address_db
Cancer
So it finds the file, but it still does not translate "Cancer".
What could that be?
Update
It works on my production server, but not on my testing server. Very strange …
Gettext translations are cached, you need to restart your server for it to pickup changes to .mo files.
It looks as if setlocale is returning false, it should return the new locale name if it worked correctly.
Is the value of $lang present in the output of locale -a? A common mistake is using e.g. de_DE rather than de_DE.utf8 or de_DE.iso88591 in your case.

How can I speed this up?

I have a script which I think is pretty basic scraping, call it what you will, but it takes on average at least 6 seconds...is it possible to speed it up? The $date variables are only there for timing the code and don't add anything significant to the time it takes. I have set two timing markers and each is approx 3 seconds between. Example URL below for testing
$date = date('m/d/Y h:i:s a', time());
echo "start of timing $date<br /><br />";
include('simple_html_dom.php');
function getUrlAddress()
{
$url = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
return $url .'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
}
$date = date('m/d/Y h:i:s a', time()); echo "<br /><br />after geturl $date<br /><br />";
$parts = explode("/",$url);
$html = file_get_html($url);
$date = date('m/d/Y h:i:s a', time()); echo "<br /><br />after file_get_url $date<br /><br />";
$file_string = file_get_contents($url);
preg_match('/<title>(.*)<\/title>/i', $file_string, $title);
$title_out = $title[1];
foreach($html->find('img') as $e){
$image = $e->src;
if (preg_match("/orangeBlue/", $image)) { $image = ''; }
if (preg_match("/BeaconSprite/", $image)) { $image = ''; }
if($image != ''){
if (preg_match("/http/", $image)) { $image = $image; }
elseif (preg_match("*//*", $image)) { $image = 'http:'.$image; }
else { $image = $parts['0']."//".$parts[1].$parts[2]."/".$image; }
$size = getimagesize($image);
if (($size[0]>110)&&($size[1]>110)){
if (preg_match("/http/", $image)) { $image = $image; }
echo '<img src='.$image.'><br>';
}
}
}
$date = date('m/d/Y h:i:s a', time()); echo "<br /><br />end of timing $date<br /><br />";
Example URL
UPDATE
This is actual what timing markers show:
start of timing 01/24/2012 12:31:50 am
after geturl 01/24/2012 12:31:50 am
after file_get_url 01/24/2012 12:31:53 am
end of timing 01/24/2012 12:31:57 am
http://www.ebay.co.uk/itm/Duke-Nukem-Forever-XBOX-360-Game-BRAND-NEW-SEALED-UK-PAL-UK-Seller-/170739972246?pt=UK_PC_Video_Games_Video_Games_JS&hash=item27c0e53896`
It's probably the getimagesize function - it is going and fetching every image on the page so it can determine the size. Maybe you can write something with curl to get the header only for Content-size (though, actually, this might be what getimagesize does).
At any rate, back in the day I wrote a few spiders and it's kind of slow to do, with internet speeds better than ever it's still a fetch for each element. And I wasn't even concerned with images.
I'm not a PHP guy, but it looks to me like you're going out to the web to get the file twice...
First using this:
$html = file_get_html($url);
Then again using this:
$file_string = file_get_contents($url);
So if each hit takes a couple of seconds, you might be able to reduce your timing by finding a way to cut this down to a single web-hit.
Either that, or I'm blind. Which is a real possibility!

echo vs file_put_contents using preg_match_all

<?php
$start_date = "20111101";
$todays_date = date('Ymd');
$html = file_get_contents("http://online.wsj.com/mdc/public/page/2_3021-tradingdiary2-{$start_date}.html?mod=mdc_pastcalendar");
preg_match_all(
'#<td style="text-align:left;padding-top:18px;" valign="bottom" class="colhead">(.*?)</td>#',
$html,
$EXCHANGE,
PREG_PATTERN_ORDER);
preg_match_all(
'#<td class="num">(\d.\d\d)</td>#',
$html,
$TRIN,
PREG_PATTERN_ORDER);
echo "{$EXCHANGE[0][0]}, \r";
echo "TRIN : {$TRIN[0][0]}, \r";
echo "{$EXCHANGE[0][1]}, \r";
echo "TRIN : {$TRIN[0][1]}, \r";
echo "{$EXCHANGE[0][2]}, \r";
echo "TRIN : {$TRIN[0][2]}, \r";
echo "{$EXCHANGE[0][3]}, \r";
echo "TRIN : {$TRIN[0][3]}, \r";
// write this to a file
$WSJData = 'WJSData.csv';
$WriteMe = "{$TRIN[0][0]}, {$TRIN[0][1]}, {$TRIN[0][2]}, {$TRIN[0][3]}";
file_put_contents($WSJData, $WriteMe );
?>
Why is the output in WSJData.csv different from the echo output? Why do I get the text I removed with the preg_match_all function in my CSV file?
If you want to write the result of some echo calls to a file, use:
ob_start(create_function('$a','file_put_contents(FILENAME,$a); return $a;'));
echo ...
echo ...
...
echo ...
ob_end_flush();
This will ensure that what is printed is what goes in the file.
Sorry, it seems to me that you have some other error in your script. I reduced it to "the simplest program that works" to reproduce the error. Here is what I got:
<?php
$TRIN = array( array("E0","E1","E2","E3") );
echo "TRIN : {$TRIN[0][0]} / ";
echo "TRIN : {$TRIN[0][1]} / ";
echo "TRIN : {$TRIN[0][2]} / ";
echo "TRIN : {$TRIN[0][3]} \n";
// write this to a file
$WSJData = 'WJSData.csv';
$WriteMe = "{$TRIN[0][0]}, {$TRIN[0][1]}, {$TRIN[0][2]}, {$TRIN[0][3]}";
file_put_contents($WSJData, $WriteMe );
echo file_get_contents($WSJData);
And the output is:
$ php test.php
TRIN : E0 / TRIN : E1 / TRIN : E2 / TRIN : E3
E0, E1, E2, E3
The first line of output is from the echoes. The second is from "file_get_contents".
The substitution works fine. Indeed, it occurs when assigning the variables, not when echoing or saving to the file.
BTW, I would recommend using \n instead of \r. The second one will not advance a line, but overwrite the current one (just in the console as it would in the printer), and I suspect that that's not what you wanted.

Categories