底下的內容參考 PHP 程式: ldapsearch 輸出內容 (LDIF) 轉 UTF-8 編碼 « Jamyy’s Weblog
# 建立 php 的轉換檔
# vim /usr/local/bin/utf8ldif.php
<?php
function fn_output($str) {
if (strpos($str,":: ") > 0) {
//解 Base64 編碼
//當 ldap 欄位名稱後面接的是兩個冒號即表示該欄位內容為 Base64 編碼
$head = substr($str,0,strpos($str," ")-1);
$body = substr($str,strpos($str," ")+1);
$str = $head . " " . base64_decode($body) . "n";
} else if (preg_match('/x5c[A-F0-9][A-F0-9]x5c[A-F0-9][A-F0-9]/',$str)) {
//解 URL 編碼
//URL 編碼出現在註解 (#), ldapsearch -LLL 可取消輸出註解內容
$str = urldecode(str_replace("","%",$str));
}
if (!preg_match('/n$/',$str)) {
//如果處理過後的字串沒有換行符號 (n) 就塞一個給他
$str .= "n";
}
return($str);
}
$line_old = "";
$line_merge = "";
$params = count($argv);
if ($params == 1) {
//未給參數時, 開啟 STDIN 串流
$f = fopen("php://stdin","r");
} else {
//開啟指定檔案
$f = fopen("$argv[1]","r");
}
while (!feof($f)) {
$line = fgets($f);
if (substr($line,0,1) == " ") {
//若該行行首為空白字元, 表示因內容過長而斷行
//以 line_merge 變數合併各段落
if ($line_merge == "") {
$line_merge = trim($line_old) . trim($line);
} else {
$line_merge .= trim($line);
}
} else if ($line_merge > "") {
//輸出合併好的內容
echo fn_output($line_merge);
$line_merge = "";
} else {
//輸出一般內容
echo fn_output($line_old);
}
$line_old = $line;
}
fclose($f);
?>
[@more@]
1. 安裝 php 套件
# yum install php-cli
2. 進行測試
# /usr/bin/ldapsearch -x -b “ou=s0101,ou=student,ou=tces,dc=ilc,dc=edu,dc=tw” uid=s0101129 | php /usr/local/bin/utf8ldif.php
# extended LDIF
#
# LDAPv3
# base <ou=s0101,ou=student,ou=tces,dc=ilc,dc=edu,dc=tw> with scope subtree
# filter: uid=s0101129
# requesting: ALL
#
# s0101129, s0101, student, tces, ilc.edu.tw
dn: uid=s0101129,ou=s0101,ou=student,ou=tces,dc=ilc,dc=edu,dc=tw
uid: s0101129
cn: 五仁25男陳※駿
sn: 五仁25男陳※駿
mail: s0101129@smail.ilc.edu.tw
objectClass: person
objectClass: organizationalPerson
objectClass: inetOrgPerson
objectClass: posixAccount
objectClass: top
objectClass: shadowAccount
shadowMin: 0
shadowMax: 99999
shadowWarning: 7
shadowExpire: 17774
loginShell: /sbin/nologin
uidNumber: 1784
gidNumber: 1075
homeDirectory: /home/s0101/s0101129
# search result
search: 2
result: 0 Success
# numResponses: 2
# numEntries: 1