the_title gives me the page’s title not the post title in the following code

You are using the default page loop and it will output the current page attributes like title or other. You should create your own loop with custon query instead. See WP_Query or get_posts.

Example

$query = new WP_Query(array(
   'post_type' => 'post',
   'posta_status' => 'publish',
));

if($query->have_posts()){
    while($query->have_posts()){
        $query->the_post();
        echo get_the_title();
    }
    wp_reset_postdata();
}