I want to retrieve some data from wordpress via this link
https://domain/wp-json/wp/v2/posts/
I have created a function in the controller like this and it runs fine when I do the var_dump
command
$url = 'https://sumbermulyo-jombang.desa.id/wp-json/wp/v2/posts?_embed';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);
curl_close($curl);
$hasil = json_decode($response);
$data['posts'] = $hasil;
//var_dump(json_decode($response, true));
$this->load->view('layouts/dashboard/header');
$this->load->view('layouts/dashboard/sidebar');
$this->load->view('pages/dashboard/home',$data);
$this->load->view('layouts/dashboard/footer');
the problem is that I still don't really understand how to display the result of the controller to the CodeIgniter view, when I do a foreach in the view like this
<?php foreach($posts as $post) : ?>
<tr>
<td><?=$post['id']?></td>
<td><?=$post['title']?></td>
<td><?=$post['link']?></td>
</tr>
<?php endforeach;?>
if there is a mistake in the case I ask here or there is a part that is not clear, let me correct it and explain it, thanks for the assistance
edit
the real problem is that it turns out that the generated JSON is a nested JSON, so I'll answer my own question because I've got the solution.
CodePudding user response:
Try With This
<?php foreach($posts as $post) : ?>
<tr>
<td><?=$post->id;?></td>
<td><?=$post->title;?></td>
<td><?=$post->link;?></td>
</tr>
<?php endforeach;?>
If the result in array of object,you will change the $post['id'] to $post->id.
CodePudding user response:
this is the solution i got few days ago
<?php
$array = 0;
foreach($posts as $post) :
?>
<tr>
<td><?php echo $posts[$array]['id'];?></td>
<td><?php echo '<img src='.$posts[$array]['better_featured_image']['media_details']['sizes']['medium']['source_url'];'/>'?> </td>
<td><?php echo $posts[$array]['title']['rendered'];?></td>
<td><?php echo $posts[$array]['content']['rendered'];?></td>
<td><a href="<?php echo $posts[$array]['link'];?>">Link</a></td>
</tr>
<?php
$array ;
endforeach;
?>
at first I didn't realize and still not familiar with how to call and write the result of nested JSON