네이버 검색 api로 아래 소스를 이용해 xml을 불러오는것 까지는 했습니다.
Copy
<?phpclass NaverProxy { public function queryNaver($query, $target) { $client_id = ""; $client_secret = ""; $query=urlencode("스칼라티움"); $target="blog"; $url = "https://openapi.naver.com/v1/search/blog.xml"; $url = sprintf("%s?query=%s&display=20&start=1&sort=sim&target=blog", $url, $query); $is_post = true; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url);// curl_setopt($ch, CURLOPT_GET, $is_post); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $headers = array(); $headers[] = "X-Naver-Client-Id: ".$client_id; $headers[] = "X-Naver-Client-Secret: ".$client_secret; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $data = curl_exec ($ch); curl_close ($ch); return $data; } } $naverproxy = new NaverProxy(); echo $naverproxy -> queryNaver($_POST['query'], $_POST['target']);?>
결과는 http://test.thedirectwedding.com/blog.html 과 같이 제대로 결과를 불러옵니다
문제는 불러온 값에서 제가 사용하고 싶은 부분만 변수로 지정해서 리스트 형식으로 뽑고 싶은데요
예를 들어 하이퍼링크 부분과 제목부분만 변수화해서 <a html="하이퍼링크">제목</a>
이런식으로 사용하려면 어떻게 해야되는걸까요? 제가 알기론 이런걸 파싱이라고 하는것 같은데
제가 워낙 초짜라 그런건 잘 몰라서요...알려주시거나 참고 할 수 있는 예제라도 좀 알려주시면
정말 감사드리겠습니다.
답변 2개 / 댓글 3개
채택된 답변
+20 포인트
9년 전
Copy
<?php
class NaverProxy {
public function queryNaver($query, $target) {
$client_id = "";
$client_secret = "";
$query=urlencode("스칼라티움");
$target="blog";
$url = "https://openapi.naver.com/v1/search/blog.xml";
$url = sprintf("%s?query=%s&display=20&start=1&sort=sim&target=blog", $url, $query);
$is_post = true;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// curl_setopt($ch, CURLOPT_GET, $is_post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = array();
$headers[] = "X-Naver-Client-Id: ".$client_id;
$headers[] = "X-Naver-Client-Secret: ".$client_secret;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec ($ch);
curl_close ($ch);
return $data;
}
}
$naverproxy = new NaverProxy();
// XML파일에서 원하는 항목만 추출하기
//echo $naverproxy -> queryNaver($_POST['query'], $_POST['target']);
$xmlstring = $naverproxy -> queryNaver($_POST['query'], $_POST['target']);
$xml = simplexml_load_string($xmlstring) or die("에러: 객체를 생성할 수 없습니다");
$items = $xml->channel->item;
foreach($items as $item){
echo '<a href="' . $item->link . '">' . $item->title . '</a><br>';
}
?>
답변에 대한 댓글 3개
kujira
9년 전
kujira
9년 전
foreach 부분을 아래와 같이 수정했더니 오류는 발생하지 않는데 결과가 출력이 되지 않고 빈 화면만 뜨고 있습니다...ㅠㅠ
[code]
if(!empty($items)){
foreach($items as $item){
echo '<a href="' . $item->link . '">' . $item->title . '</a><br>';
}
}
[/code]
[code]
if(!empty($items)){
foreach($items as $item){
echo '<a href="' . $item->link . '">' . $item->title . '</a><br>';
}
}
[/code]
버스라이프
9년 전
똑같이 적용을 했는데 에러가 납니다.
객체를 생성할 수 없다는데요, 왜 XML이 생성이 안되는 건지 궁금하네요.
API ID, secret 키 모두 제대로 입력을 했는데 말이죠. 소스도 건드린데 없는데 왜 에러가 날까요?
답변을 작성하려면 로그인이 필요합니다.
그런데 Warning: Invalid argument supplied for foreach() in /home/testsite/blog.html on line 39
애러가 발생하는군요 뭐가 빠진게 있나요?