Extra Form
PHP PHP 5.x
CMS XpressEngine

수고들 많으 십니다.

다름이 아니라

xe의 DB내용을 Json으로 가지고 오고 싶은데요

 

<?php

$db_host = "localhost";

$db_user = "xxx";

$db_passwd = "xxx";

$db_name = "xxx";

 
mysql_connect($db_host, $db_user, $db_passwd);

mysql_select_db($db_name);

mysql_query('set session character_set_connection=utf8;');

mysql_query('set session character_set_results=utf8;');

mysql_query('set session character_set_client=utf8;');

 
$result = mysql_query("SELECT * FROM xe_documents;");

$rows = array();

 
while ($row = mysql_fetch_assoc($result)) {

$JSONres = array (

"title" => urlencode($row['title']),

"content" => urlencode($row['content'])

);

array_push($rows, $JSONres);

}

 
echo(strip_tags(urldecode(json_encode($rows))));

?>

위와 같이 PHP코드를 작성했는데요

실행해보면 [] 요런 문자만 나오고 아무것도 안나오네요

혹시 뭐가 잘못되었는지 알 수 있을까요?

  • profile

    개발하다가 뭔가가 잘 안 될 때는 최종 결과만 보지 말고 중간 단계를 꼼꼼하게 확인하는 것이 중요합니다.
    - DB 접속은 성공했는가? 체크하는 로직이 전혀 안 보이네요.
    - 23줄의 쿼리는 성공했는가? ($result를 찍어보기)
    - 28줄에서 $row를 제대로 받아왔는가? ($row를 찍어보기)
    - json_encode 하기 전에 $rows를 일단 print_r로 찍어보면 어떻게 나오는가?
    등등, 어디에서 문제가 발생했는지 확인해볼 수 있는 타이밍이 여러 군데 있습니다.

    그리고 굳이 urlencode해서 저장한 것을 다시 urldecode해서 표시하고 strip_tags까지 하는 이유를 모르겠습니다. 명확한 의도 없이 그냥 쓸만해 보이는 함수를 이것저것 붙여보는 카고컬트의 냄새가 납니다.

  • profile profile
    최근 데이터를 가져와서 출력하는 것을 만들다 보니까 어디부터 잘못된 건지 디버그로 순서대로 찍어보면 잘못된 출발점 찾기 쉽더라구요!
  • ?

    <?php
    $conn = mysqli_connect('localhost', 'id', 'pw', 'db');
    $result = mysqli_query($conn, 'SELECT * FROM xe_documents;');
    $rows = array();
    while ($row = mysqli_fetch_assoc($result)) {
    $JSONres = array(
    'title' => urlencode($row['title']),
    'content' => urlencode($row['content'])
    );
    $rows[] = $JSONres;
    }
    echo(strip_tags(urldecode(json_encode($rows))));

  • profile
    양희은님 답변 응용하여 해결하였습니다.
    좋은 답변들 감사합니다. (__)