Why the Loop not properly Looping through the data?

Issue

<?php
$id = array(
    "UC4MubF2asPHQbXN44DVNeXg",
    "UCXuDgoo_oiZf8UkIXs3Y_kw",
    "UCMnDuOzzJrWzr5tfemDcqlQ",
    "UC9FH1mkHLFQuPPEPu9CfR1A",
    "UCfyEAw41i7PRetP2erYf9dg",
);

// Getting Emails from DB and Looping with Channel Title and Video Title

$conn = mysqli_connect("localhost","username","password","dbname");
$query = "SELECT * FROM prospects ORDER BY email";
$rows = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($rows)) {
    
    $to[] = $row['email'];
}

$size = sizeof($id);
//echo "<br>Number of channel Ids: ".$size."<br><br>";

// Looping each Url for Each Email to get Data 

foreach($to as $t){
    echo $t."<br>";
    for ($i = 0; $i < $size; $i++) {
        $url = "https://www.youtube.com/channel/$id[$i]";
        // echo $url."<br>";

        $channel = trim(explode('https://www.youtube.com/channel/', $url)[1]);
        // echo $channel."<br>";
    
        $rss = "https://www.youtube.com/feeds/videos.xml?channel_id=$channel";
        // echo $rss."<br>";
        
        $xml = simplexml_load_file($rss);    

        $title = $xml->title;
        // echo $title."<br>";
            
        $videoTitle = $xml->entry[0]->title;
        // echo $videoTitle."<br>";
        $id[$i] = $xml->id;
        // echo $id[$i]."<br>";   
        // $idOnly = substr($id[$i] , strpos($id[$i] , "yt:channel:") + 11);    
        // echo $idOnly."<br>";

        $pub[$i] = $xml->entry[0]->published;
        // echo $pub[$i]."<br>";
        $realDate_ = new DateTime($pub[$i]);
        // var_dump($realDate_);
        $realDate2_ = $realDate_->format("D, d M Y")."<br>";
        //echo $realDate2_;    

        $today_ = new DateTime();
        //     $today2_ = $today_->format("D, d M Y")."<br>";
        // echo $today2_;
        // if ($today2_ == $realDate2_) {
        // echo "true";

        // This is the Result with Every Email

        echo $content = "• <a href='https://bladingflix.com/render.php?email=$t&channel=$idOnly'>".$title." - ".$videoTitle."</a><br>";
        // }
    }
}
?>

For the First Email the Data Shows Properly but in for the others

Purpose = get collected links add the user email to each url repeat for each.

Solution

Please make below changes in your existing code

In the second for() loop you are replacing the $id array as below

$id[$i] = $xml->id;

Instead of replacing the $id[$i] value, create new variable as below

$xmlId = $xml->id;
$idOnly = substr($xmlId, strpos($xmlId , "yt:channel:") + 11);

And please uncomment the $idOnly variable.
It will work. And try to refactor this code.

Answered By – prashant

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published