Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Last week I wanted to convert some simplified Chinese characters into traditional ones. I found a deceptively nice looking shell one-liner, which today I found out was 20% error prone.

So I did some research. The mediawiki codebase contains conversion tables that take the idiosyncratic nature of simplified orthography into account, and someone already wrote a nice helper library full of dummy classes and functions, called mediawiki-zhconverter. So it appeared I could have my one-liner, which I would prefer looked something like this, stconvert being the name of the script I'm writing:

$cat simplifiedstory | stconvert > traditionalstory

However, mediawiki is entirely PHP, and I have never written any PHP, so I don't know how it deals with shell variables. As you can see below, simply putting '$argv' where a string would go does not achieve my goal.

#!/usr/bin/php
<?php

define("MEDIAWIKI_PATH", "/home/a1/mediawiki-1.13.0/");
require_once "mediawiki-zhconverter.inc.php";
echo MediaWikiZhConverter::convert($argv, "zh-tw") , ",";

?>
share|improve this question

1 Answer 1

up vote 1 down vote accepted

You almost had it. $argv is an array, similar to perl. $argv[0] is the script itself, like $0 in shell, or $ARGV[0] in perl. $argv[1] would be the first argument passed to the script, but your usage would probably change since you can do the cat in your php script. Assuming your php script is stconvert, usage would now be stconvert simplifiedstory > traditionalstory.

#!/usr/bin/php
<?php

define("MEDIAWIKI_PATH", "/home/a1/mediawiki-1.13.0/");
require_once "mediawiki-zhconverter.inc.php";

$text = shell_exec("cat $argv[1]");
echo MediaWikiZhConverter::convert($text, "zh-tw") , ",";

?>
share|improve this answer
    
it works beautifully. i guess i didn't need that extra comma at the end of the echo... –  ixtmixilix Nov 2 '11 at 18:35
    
i'm glad to hear that. –  Tim Kennedy Nov 2 '11 at 19:09
1  
I am the developer of mediawiki-zhconverter, I am also glad that you find my code useful :) –  tszming Nov 3 '11 at 2:42
1  
As a general note, for those looking for a way to use stdin and stdout: PHP has predefined streams and file descriptors you can use. For example: echo str_replace('foo', 'bar', file_get_contents('php://stdin'); would replace all foo with bar in the piped input. If you want a file handle, use STDIN. For example, when piping a CSV file: while (($record = fgetcsv(STDIN))) { print_r($record); }. –  janmoesen Nov 3 '11 at 19:37
    
thanks @janmoesen, for the PHP and STDIN tip. –  Tim Kennedy Nov 4 '11 at 1:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.