2010-08-13 7 views
8

모든 PHP 프로젝트 (약 25 개!), 배치, 레포 동기화, 데이터베이스 내보내기/내보내기 등과 같은 일상적인 작업에 도움이되는 몇 가지 sh 스크립트가 있습니다. 등Sh/Bash 및 PHP에서 구성 매개 변수를 구문 분석하는 가장 좋은 방법/가장 쉬운 방법

남반구 스크립트는 내가 관리하는 모든 프로젝트에 대해 동일하므로 프로젝트에 의존 개의 다른 매개 변수를 저장하는 구성 파일이 있어야합니다 : 난 그냥 깨끗한을 찾을 필요가

# example conf, the sintaxys only needs to be able to have comments and be easy to edit. 
host=www.host.com 
[email protected] 
password=xxx 

을 이 구성 파일을 sh 스크립트에서 읽거나 (구문 분석 할) 동시에 PHP 스크립트에서 동일한 매개 변수를 읽을 수있는 방법. XML을 사용할 필요가 없습니다.

당신은 이것을위한 좋은 해결책을 알고 있습니까?

길레르모

답변

6

pavanlimo가 보여준대로 파일을 소스하지 않으려면 다른 옵션으로 th 루프를 사용하여 전자 변수 : PHP에서

while read propline ; do 
    # ignore comment lines 
    echo "$propline" | grep "^#" >/dev/null 2>&1 && continue 
    # if not empty, set the property using declare 
    [ ! -z "$propline" ] && declare $propline 
done < /path/to/config/file 

동일한 기본 개념이 적용

// it's been a long time, but this is probably close to what you need 
function isDeclaration($line) { 
    return $line[0] != '#' && strpos($line, "="); 
} 

$filename = "/path/to/config/file"; 
$handle = fopen($filename, "r"); 
$contents = fread($handle, filesize($filename)); 
$lines = explode("\n", $contents); // assuming unix style 
// since we're only interested in declarations, filter accordingly. 
$decls = array_filter($lines, "isDeclaration"); 
// Now you can iterator over $decls exploding on "=" to see param/value 
fclose($handle); 
+0

고마워! 좋은 소리. 하지만 그것은 쉽게 PHP에서 읽기에서 posibility를 reolve 나는 추측 ... – Guillermo

+0

가능한 PHP 솔루션을 포함하도록 편집. –

+0

당신의 anwer 주셔서 감사합니다. 나는 그것을 고려할 것이지만 위의 솔루션을 더 쉽게 고려해 보겠습니다 :-) – Guillermo

17

스크립트 파일을 다른 sh 파일로 가져 오기만하면됩니다.

예 :

conf-file.sh :

# A comment 
host=www.host.com 
[email protected] 
password=xxx 

귀하의 실제 스크립트를

#!/bin/sh 

. ./conf-file.sh 

echo $host $administrator_email $passwword 

그리고 같은 conf의 파일이 PHP 구문을 분석 할 수 있습니다 http://php.net/manual/en/function.parse-ini-file.php

+0

감사합니다. 당신의 솔루션은 쉽게 들리지만 INI 파일 주석은 ";" SH처럼 "#"이 아니라. 그 맞습니까? – Guillermo

+0

실제로는 '#'을 계속 사용할 수 있지만> = v5.3을 사용하는 경우 경고가 표시됩니다. 더 낮은 버전이면 경고가 표시되지 않습니다. http://php.net/manual/en/function.parse-ini-file.php – pavanlimo

1

은 PHP, 사용으로부터

#!/bin/bash 
#bash 4 
shopt -s extglob 
while IFS="=" read -r key value 
do 
    case "$key" in 
    !(#*)) 
    echo "key: $key, value: $value" 
    array["$key"]="$value" 
    ;; 
    esac 
done <"file" 
echo php -r myscript.php ${array["host"]} 

다음 SH/떠들썩한 파티에서 ini 파일을 파싱 argv

관련 문제