Gilbert e. Gilbert e. - 5 months ago 34
PHP Question

cURL: variable in foreach loop

Good day, can anyone help me to figure out what is wrong in my code or if I coded it the wrong way.

The curl part is ok my problem is when I started to get the file using foreach loop the result is broken image.

I've try it in array but nothings happen. I'm new with this, maybe I'm missing something here

Here is my code:

<?php
$url = "http://XXXXXXXXXXXXXX"; //Base Url
$parameters = ['mode' => 'contributors']; // riders, current_rounds, contributors, season_entries
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
curl_setopt($ch,CURLOPT_HTTPHEADER, ['x-weplaymedia-authorisation:XXXXXXXXXXXXX']);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch); // Execute

$arr = json_decode($result,true); // Dump result here.

//print_r($arr);


If you run
print_r($arr);
it will display array of fields.

But when I try to point certain fields ([fwcContributors]) in my foreach loop code im getting a broken images.

Here is the image of array:

here is the image of array

Here is the result

here is the result

What I want is to display their profile picture from [profilePicture] and username from [userName].

$i=0;
foreach ($arr['fwcContributors'] as $val)
{
if($i++ == 5);
echo '<tbody >';
echo '<tr style="transform: skewX(-20deg);">';
echo '<td>';
echo '<img src='.($val['profilePicture']) .' style="transform: skewX(20deg);">' . htmlspecialchars($val['userName']);
echo '</td>';
echo '</tr>';
}

?>


Thank you in advance.

Answer

There are nested arrays in fwcContributors, of which you probably want ContributorList to iterate over:

foreach ($arr['fwcContributors']['ContributorList'] as $val)
{
    echo '<tbody >';
    echo '<tr style="transform: skewX(-20deg);">';
    echo '<td>';
    echo '<img src='.($val['profilePicture']) .' style="transform: skewX(20deg);">' . htmlspecialchars($val['userName']);
    echo '</td>';
    echo '</tr>';
}

(Took the $i statements out, as they don't seem to do anything.)