api값을 wr_content에 등록할때 한줄만 등록되는데 전체값 등록 가능하게 하려면 어떻게 해야할까요ㅠㅠ

api값을 wr_content에 등록할때 한줄만 등록되는데 전체값 등록 가능하게 하려면 어떻게 해야할까요ㅠㅠ

QA

api값을 wr_content에 등록할때 한줄만 등록되는데 전체값 등록 가능하게 하려면 어떻게 해야할까요ㅠㅠ

본문

그누보드경로/nn 폴더안에 composer, GuzzleHttp\Client 설치 후

노션 api를 이용해서 특정 페이지의 하위 페이지들의 값을 가져와서

html태그로 wr_content로 등록을 하는데 페이지 첫번째줄의 값만 등록됩니다ㅠㅠ

이 문제가 일주일 넘게 해결이 안돼서 죽겠습니다ㅠㅠ 제가 php 초보라서 검색이랑 챗지피티로 코드를 만들었는데 값이 넘어가질 않네요ㅠㅠ

wr_content를 롱텍스트로도 변경해봤습니다ㅠㅠㅠ

 

제가 만든 코드는

<?php

require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

date_default_timezone_set('Asia/Seoul');

$notionToken = 'api키값';

$client = new Client([
    'base_uri' => 'https://api.notion.com/v1/',
    'headers' => [
        'Authorization' => 'Bearer ' . $notionToken,
        'Notion-Version' => '2022-06-28',
        'Content-Type' => 'application/json',
    ],
]);

function fetchContent($client, $blockId, $isToggleable = false) {
    $content = [];
    $nextCursor = null;

    do {
        try {
            $response = $client->get("blocks/{$blockId}/children", [
                'query' => [
                    'start_cursor' => $nextCursor,
                    'page_size' => 100,
                ],
            ]);

            $data = json_decode($response->getBody()->getContents(), true);

            if (isset($data['results'])) {
                foreach ($data['results'] as $block) {
                    if ($isToggleable || !isset($block['is_toggleable']) || !$block['is_toggleable']) {
                        if (isset($block['has_children']) && $block['has_children']) {
                            $block['children'] = fetchContent($client, $block['id'], $isToggleable);
                        }
                    }
                    $content[] = $block;
                }
            }
            
            $nextCursor = $data['next_cursor'] ?? null;
        } catch (RequestException $e) {
            logError($e);
            return [];
        }
    } while ($nextCursor);

    return $content;
}

function fetchSubPages($client, $pageId, $isToggleable = false) {
    $subPages = [];
    $nextCursor = null;

    do {
        try {
            $response = $client->get("blocks/{$pageId}/children", [
                'query' => [
                    'start_cursor' => $nextCursor,
                    'page_size' => 100,
                ],
            ]);

            $data = json_decode($response->getBody()->getContents(), true);

            if (isset($data['results'])) {
                foreach ($data['results'] as $block) {
                    if (in_array($block['type'], ['child_page', 'child_database'])) {
                        $pageId = $block['id'];
                        $block['created_time'] = $block['created_time'];
                        $block['content'] = fetchContent($client, $block['id'], $isToggleable);
                        
                        $pageResponse = $client->get("pages/{$pageId}");
                        $pageData = json_decode($pageResponse->getBody()->getContents(), true);
                        $block['cover'] = $pageData['cover'] ?? null;

                        $subPages[] = $block;
                    }
                }
            }

            $nextCursor = $data['next_cursor'] ?? null;
        } catch (RequestException $e) {
            logError($e);
            return [];
        }
    } while ($nextCursor);

    return $subPages;
}

function logError($e) {
    $logMessage = sprintf(
        "[%s] %s: %s\n%s\n",
        date('Y-m-d H:i:s'),
        get_class($e),
        $e->getMessage(),
        $e->getTraceAsString()
    );
    file_put_contents('error_log.txt', $logMessage, FILE_APPEND);
}

function convertTextToHtml($annotations) {
    $bold = isset($annotations['bold']) && $annotations['bold'] ? 'bold' : '';
    $italic = isset($annotations['italic']) && $annotations['italic'] ? 'italic' : '';
    $strikethrough = isset($annotations['strikethrough']) && $annotations['strikethrough'] ? 'strikethrough' : '';
    $underline = isset($annotations['underline']) && $annotations['underline'] ? 'underline' : '';
    $code = isset($annotations['code']) && $annotations['code'] ? 'code' : '';
    $color1 = '';
    $color2 = '';
    if (isset($annotations['color']) && strpos($annotations['color'], '_background') !== false) {
        $color1 = 'bg-' . str_replace('_background', '', $annotations['color']);
    } elseif (isset($annotations['color'])) {
        $color2 = $annotations['color'];
    }
    return [$bold, $italic, $strikethrough, $underline, $code, $color1, $color2];
}

function blockToHtml($block, &$counter = 1) {
    $type = $block['type'];
    $html = '';
    
    $richText = [];
    if (isset($block[$type]['rich_text'])) {
        $richText = $block[$type]['rich_text'];
    } elseif (isset($block[$type]['text'])) {
        $richText = $block[$type]['text'];
    }

    $annotations = [];
    foreach ($richText as $text) {
        if (isset($text['annotations'])) {
            $annotations = $text['annotations'];
            break;
        }
    }

    $annotationValues = array_map('htmlspecialchars', convertTextToHtml($annotations));
    list($bold, $italic, $strikethrough, $underline, $code, $color1, $color2) = $annotationValues;
    
    $blockcolor = '';
    if (isset($block[$type]['color']) && $block[$type]['color'] !== 'default') {
        if (strpos($block[$type]['color'], '_background') !== false) {
            $blockcolor = 'bg-' . str_replace('_background', '', $block[$type]['color']);
        } else {
            $blockcolor = $block[$type]['color'];
        }
    }

    $classAttributes = implode(' ', array_filter([$bold, $italic, $strikethrough, $underline, $code, $color1, $color2, $blockcolor]));
    $classAttributeString = 'class="notion-' . htmlspecialchars($type ?? '') . ' ' . $classAttributes . '"';

    switch ($type) {
        case 'divider':
            $html = '<div class="notion-divider"></div>';
            break;
        case 'bulleted_list_item':
            $html = '<ul ' . $classAttributeString . '><li>' . getTextContent($block['bulleted_list_item']['rich_text'], $block) . '</li></ul>';
            if (isset($block['children'])) {
                foreach ($block['children'] as $child) {
                    $html .= '<ul>' . blockToHtml($child, $counter) . '</ul>';
                }
            }
            break;
        case 'callout':
            $emoji = $block['callout']['icon']['emoji'] ?? '';
            $html = '<div ' . $classAttributeString . '>' . $emoji . ' ' . getTextContent($block['callout']['rich_text'], $block) . '</div>';
            if (isset($block['children'])) {
                foreach ($block['children'] as $child) {
                    $html .= blockToHtml($child, $counter);
                }
            }
            break;
        case 'child_page':
            $html = '<div ' . $classAttributeString . '>' . htmlspecialchars($block['child_page']['title']) . '</div>';
            break;
        case 'child_database':
            $html = '<div ' . $classAttributeString . '>' . htmlspecialchars($block['child_database']['title']) . '</div>';
            break;
        case 'toggle':
            $html = '<div class="notion-toggles">';
            $html .= '<button type="button" class="notion-togglebtn">▶️</button>';
            $html .= '<div ' . $classAttributeString . '>' . getTextContent($block['toggle']['rich_text'], $block) . '</div></div>';
            if (isset($block['children'])) {
                $html .= '<div class="notion-children notion-toggle-cont">';
                foreach ($block['children'] as $child) {
                    $html .= blockToHtml($child, $counter);
                }
                $html .= '</div>';
            }
            break;
    }
    return $html;
}

function getTextContent($textArray, $block = null) {
    $content = '';
    foreach ($textArray as $text) {
        $content .= htmlspecialchars($text['text']['content']);
    }
    return $content;
}

function getTableContent($table) {
    $html = '';
    foreach ($table['rows'] as $row) {
        $html .= '<tr>';
        foreach ($row['cells'] as $cell) {
            $html .= '<td>' . getTextContent($cell['rich_text']) . '</td>';
        }
        $html .= '</tr>';
    }
    return $html;
}

function getTableRowContent($tableRow) {
    $html = '';
    foreach ($tableRow['cells'] as $cell) {
        $html .= '<td>' . getTextContent($cell['rich_text']) . '</td>';
    }
    return $html;
}

$pageId = '페이지아이디';
$subPages = fetchSubPages($client, $pageId, true);

include_once('../common.php');
include_once('../_common.php');

$bo_table = "test"; 
$write_table = $g5['write_prefix'] . $bo_table;
if ($member['mb_id']) {
    $mb_id = $member['mb_id'];
    $wr_name = $member['mb_name'];
    $wr_password = $member['mb_password'];
    $wr_email = $member['mb_email'];
} else {
    $mb_id = "test";
    $wr_name = "test";
    $wr_password = get_encrypt_string($wr_password);
    $wr_email = "test이메일.com";
}

$mode = 'html1';
$categorys = 'category1';

function escape_content($content) {
    global $g5;
    return mysqli_real_escape_string($g5['connect_db'], $content);
}

foreach ($subPages as $subPage) {
    $counter = 1;
    $sub_title = htmlspecialchars($subPage['child_page']['title']);
    $sub_date = date('Y-m-d H:i:s', strtotime($subPage['created_time']));
    $coverUrl = $subPage['cover']['external']['url'] ?? $subPage['cover']['file']['url'] ?? '';
    $cover_url = htmlspecialchars($coverUrl);
    
    $sub_contents = '';
    foreach ($subPage['content'] as $block) {
        $sub_contents .= blockToHtml($block, $counter);
    }
        
    echo $sub_title;
    echo $sub_date;
    echo $cover_url;
    echo $sub_contents;
    
    $wr_num = get_next_num($write_table);
    $sql = "INSERT INTO $write_table
        SET wr_id = '',
            wr_num = '{$wr_num}',
            wr_comment = 0,
            ca_name = '{$categorys}',
            wr_subject = '{$sub_title}',
            wr_content = '{$sub_contents}',
            mb_id = '{$mb_id}',
            wr_password = '$wr_password',
            wr_name = '$wr_name',
            wr_email = '$wr_email',
            wr_datetime = '{$sub_date}',
            wr_last = '" . G5_TIME_YMDHIS . "',
            wr_2 = '{$cover_url}',
            wr_ip = '{$_SERVER['REMOTE_ADDR']}' ";
    sql_query($sql);
    $wr_id = sql_insert_id();
    
    sql_query("UPDATE $write_table SET wr_parent = '$wr_id' WHERE wr_id = '$wr_id'");
    sql_query("INSERT INTO {$g5['board_new_table']} (bo_table, wr_id, wr_parent, bn_datetime, mb_id) VALUES ('{$bo_table}', '{$wr_id}', '{$wr_id}', '" . G5_TIME_YMDHIS . "', '{$member['mb_id']}')");
}

sql_query("UPDATE {$g5['board_table']} SET bo_count_write = bo_count_write + " . count($subPages) . " WHERE bo_table = '{$bo_table}'");

입니다.

sub_contents의 값의 html코드가 200줄이라고 하면 첫번째 줄의 html값만 wr_content에 등록이 됩니다

<div class="notion-aa"> 이런식으로요ㅠㅠ 어떻게 하면 wr_content에 sub_contents의 전체 값이 넘어갈수있을까요..?

아무리 검색하고 챗지피티 돌려보고 해도 모르겠습니다 제발 도와주세요ㅠㅠ..

 

이 질문에 댓글 쓰기 :

답변 1

wr_content = '{addslashes($sub_contents)}', 

이렇게 변경해보시겠어요 ?

답변을 작성하시기 전에 로그인 해주세요.
전체 2,662
QA 내용 검색

회원로그인

(주)에스아이알소프트 / 대표:홍석명 / (06211) 서울특별시 강남구 역삼동 707-34 한신인터밸리24 서관 1404호 / E-Mail: admin@sir.kr
사업자등록번호: 217-81-36347 / 통신판매업신고번호:2014-서울강남-02098호 / 개인정보보호책임자:김민섭(minsup@sir.kr)
© SIRSOFT