728x90

Bootstrap 메인 화면을 Layout 할 때 Carousel (이미지 회전 화면) 기능을 쉽게 제공한다.


https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_carousel&stacked=h 는 하나의 파일로 Carousel 을 제공하는 예제다.

그런데 직접 파일명을 갯수만큼 적어주는 방법이다.


그래서 지정한 폴더의 파일명을 자동으로 읽어서 화면에 보여주도록 코드를 보완했다.


보완 전 코드

<div id="myCarousel" class="carousel slide" data-ride="carousel">
    <!-- Indicators -->
    <ol class="carousel-indicators">
        <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
        <li data-target="#myCarousel" data-slide-to="1"></li>
        <li data-target="#myCarousel" data-slide-to="2"></li>
        <li data-target="#myCarousel" data-slide-to="3"></li>
    </ol>

    <!-- Wrapper for slides -->
    <div class="carousel-inner">
        <div class="item active">
            <img src="<?php echo $g['path_image']?>carousel/01.jpg" style="width:100%;">
        </div>

        <div class="item">
            <img src="<?php echo $g['path_image']?>carousel/02.jpg" style="width:100%;">
        </div>

        <div class="item">
            <img src="<?php echo $g['path_image']?>carousel/03.jpg" style="width:100%;">
        </div>

        <div class="item">
            <img src="<?php echo $g['path_image']?>carousel/04.jpg" style="width:100%;">
        </div>
    </div>

    <!-- Left and right controls -->
    <a class="left carousel-control" href="#myCarousel" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left"></span> <span class="sr-only">Previous</span> </a>
    <a class="right carousel-control" href="#myCarousel" data-slide="next"> <span class="glyphicon glyphicon-chevron-right"></span> <span class="sr-only">Next</span> </a>
</div>


보완 후 코드

<?php
$path = $g['path_image'] . 'carousel';
$R = getFileNames($path); // 오픈하고자 하는 폴더
function getFileNames($directory) {
    $valid_formats = array("jpg", "png", "gif");// 그림 확장자 지정
    $results = array();
    $handler = opendir($directory);
    while ($file = readdir($handler)) {
        if ($file === "." || $file === "..") continue; // file명이 ".", ".." 이면 무시함
        $getExt = pathinfo($file, PATHINFO_EXTENSION); // 파일의 확장자를 구함

        if (!empty($getExt)) {
            if (in_array($getExt, $valid_formats)) {
                $results[] = $file;
            }
        }
    }
    closedir($handler);
    return $results;
}
?>
<div id="myCarousel" class="carousel slide" data-ride="carousel">
    <!-- Indicators -->
    <ol class="carousel-indicators">
        <?php
        for ($i = 0; $i < count($R); $i++) {
            if ($i == 0){
                echo '<li data-target="#myCarousel" data-slide-to="$i" class="active"></li>';
            } else {
                echo '<li data-target="#myCarousel" data-slide-to="$i"></li>';
            }
        }
        ?>
    </ol>

    <!-- Wrapper for slides -->
    <div class="carousel-inner">
        <?php
        foreach($R as $key=>$value){
            if($key == 0){
                echo '<div class="item active">';
            } else {
                echo '<div class="item">';
            }
            echo '<img src="'.$g['path_image'].'carousel/'.$value.'" style="width:100%;">';
            echo '</div>';
        }
        ?>
    </div>

    <!-- Left and right controls -->
    <a class="left carousel-control" href="#myCarousel" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left"></span> <span class="sr-only">Previous</span> </a>
    <a class="right carousel-control" href="#myCarousel" data-slide="next"> <span class="glyphicon glyphicon-chevron-right"></span> <span class="sr-only">Next</span> </a>
</div>


부트스트랩이 아닌 경우에는 bxslider 코드에 이미지 자동 읽어오기를 추가한 걸 이용하면 편하다.

http://link2me.tistory.com/1259 참조


bxslider.zip



블로그 이미지

Link2Me

,
728x90

PHP 에서 JSON 데이터를 파싱하는 방법이다.

JSON 데이터는 Local File 을 읽어오는 것과 Web 사이트에서 해당 URL 을 읽어오는 방법이 있다.

가장 먼저 파싱해야 할 데이터 형태 파악을 하는 코드부터 살펴보고자 구글링을 했더니 관련 코드가 있어서 주석을 좀 더 추가하고 이해를 돕는 걸 첨가하여 적어둔다.


 <?php
// Web JSON 파일 읽어오기
$url = 'http://ip주소/getFileList.php';
$json_string = file_get_contents($url);

// Local JSON 파일 읽어오기
//$json_string = file_get_contents('weather.json');
// 다차원 배열 반복처리
$R = new RecursiveIteratorIterator(
    new RecursiveArrayIterator(json_decode($json_string, TRUE)),
    RecursiveIteratorIterator::SELF_FIRST);
// $R : array data
// json_decode : JSON 문자열을 PHP 배열로 바꾼다
// json_decode 함수의 두번째 인자를 true 로 설정하면 무조건 array로 변환된다.

foreach ($R as $key => $val) {
    if(is_array($val)) { // val 이 배열이면
        echo "$key:<br/>";
        //echo $key.' (key), value : (array)<br />';
    } else { // 배열이 아니면
        echo "$key => $val <br />";
    }
}
?>


위 코드로 형태파악을 한 다음에 필요한 것을 파싱처리하면 된다.


Local JSON 파일을 읽어서 처리하는 걸 예제로 보자.

 [
    {
        "firstName": "길동",
        "lastName": "홍",
        "email": "jdhongv@gmail.com",
        "mobile": "010-1234-1111"
    },
    {
        "firstName": "민아",
        "lastName": "김",
        "email": "minakim@gmail.com",
        "mobile": "010-1234-3333"
    },
    {
        "firstName": "진주",
        "lastName": "마",
        "email": "jjmah@gmail.com",
        "mobile": "010-1234-5555"
    },
    {
        "firstName": "서영",
        "lastName": "이",
        "email": "sylee@gmail.com",
        "mobile": "010-1234-7777"
    }
]


<?php
// Local JSON 파일 읽어오기
$json_string = file_get_contents('data.json');
$R = json_decode($json_string, true);
// json_decode : JSON 문자열을 PHP 배열로 바꾼다
// json_decode 함수의 두번째 인자를 true 로 설정하면 무조건 array로 변환된다.
// $R : array data


foreach ($R as $row) {
    print $row['lastName'];
    print $row['firstName'];
    print ' , ';
    print $row['email'];
    print ' , ';
    print $row['mobile'];
    print '<br />';
}
?> 


결과

홍길동 , jdhongv@gmail.com , 010-1234-1111
김민아 , minakim@gmail.com , 010-1234-3333
마진주 , jjmah@gmail.com , 010-1234-5555
이서영 , sylee@gmail.com , 010-1234-7777


조금 더 복잡한 JSON 파일을 검색한 걸 테스트한다.

{
    "name": "홍길동",
    "alias": "LInk",
    "members": [
        "소원",
        "예린",
        "은하",
        "유주",
        "신비",
        "엄지"
    ],
    "albums": {
        "EP 1집": "Season of Glass",
        "EP 2집": "Flower Bud",
        "EP 3집": "Snowflake",
        "EP 4집": "THE AWAKENING"
    }
}


파싱하는 코드를 두가지로 테스트해보면 print_r 에서 결과를 다르게 보여준다.

<?php
// JSON 파일 읽어오기
$json_string = file_get_contents('weather.json');
// 다차원 배열 반복처리
$R = new RecursiveIteratorIterator(
    new RecursiveArrayIterator(json_decode($json_string, TRUE)),
    RecursiveIteratorIterator::SELF_FIRST);
// $R : array data
// json_decode : JSON 문자열을 PHP 배열로 바꾼다
// json_decode 함수의 두번째 인자를 true 로 설정하면 무조건 array로 변환된다.

print_r($R);
echo '<br />';

foreach ($R as $key => $val) {
    if(is_array($val)) {
        echo "$key:<br/>";
    } else {
        echo "$key => $val<br/>";
    }
}
?>

<?php
// Local JSON 파일 읽어오기
$json_string = file_get_contents('weather.json');
$R = json_decode($json_string, true); //
// $R : array data
// json_decode : JSON 문자열을 PHP 배열로 바꾼다
// json_decode 함수의 두번째 인자를 true 로 설정하면 무조건 array로 변환된다.

print_r($R); // 배열 요소를 출력해준다.
echo '<br />';
?>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>PHP JSON parser sample</title>
    </head>

    <body>
        <h3 id="gname">
        <?php
            echo $R['name'];
            if (array_key_exists('alias', $R))
                printf(" (%s)", $R['alias']);
        ?>
        </h3>
        <p>멤버 구성: <span id="members">
            <?php echo implode(', ', $R['members']);?></span>
        </p>
        <h3>앨범 목록</h3>
        <ul id="albums">
        <?php
            foreach ($R['albums'] as $key => $value) {
                printf("<li>%s: %s</li>\n", $key, $value);
            }
            ?>
        </ul>
    </body>
</html>


테스트에 사용한 파일 첨부


JSONwithPHP.zip


블로그 이미지

Link2Me

,