cURL: variable in foreach loop - php

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 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.

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.)

Related

nse option chain json response in table format

i have the code which is giving json response in table format using curl php. but i dont know how to display it as correct order like expiryDate uninterest for ce ChangeinopenInterest for ce strike price openInterest for pe and changeinopenInterest For pe side.
Here is the code
JSON Data Table
your text
Key
Value
<?php
$url = "https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY";
// Initialize curl`your text`
$ch = curl_init();
// Set the URL
curl_setopt($ch, CURLOPT_URL, $url);
// Return the response as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Make the request
$response = curl exec($ch);
// Close the curl session
curl close($ch);
// Decode the JSON data
$data = json_decode($response, true);
// Recursive function to display arrays in a table
function displayArray($data) {
foreach ($data as $key => $value):
echo "<tr>";
echo "<td>$key</td>";
if (is_array($value)) {
echo "<td>";
echo "<table border='1' style='padding-left: " . ($level * 20) . "px;'>";
displayArray($value);
echo "</table>";
echo "</td>";
} else {
echo "<td>$value</td>";
}
echo "</tr>";
endforeach;
}
display Array($data);
?>
</tbody>
</table>

I am trying to grav meta tags of a webpage, help me to convert this into array?

I have a code by which I can fetch meta tags of a webpage. But I want to use it to fetch data from multiple pages or sites.
I have written this test code to grab metadata of a webpage but I want to grab the metadata of multiple pages at once. I am unable to do this by myself
<?php
// Web page URL
$url = $_POST['url'];
// Extract HTML using curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data = curl_exec($ch);
curl_close($ch);
// Load HTML to DOM object
$dom = new DOMDocument();
#$dom->loadHTML($data);
// Parse DOM to get Title data
$nodes = $dom->getElementsByTagName('title');
$title = $nodes->item(0)->nodeValue;
// Parse DOM to get meta data
$metas = $dom->getElementsByTagName('meta');
$description = $keywords = '';
for($i=0; $i<$metas->length; $i++){
$meta = $metas->item($i);
if($meta->getAttribute('name') == 'description'){
$description = $meta->getAttribute('content');
}
if($meta->getAttribute('name') == 'keywords'){
$keywords = $meta->getAttribute('content');
}
}
?>
<form class="form-horizontal" method="post" action="j.php">
<textarea class="form-control" id="name" placeholder="https://google.com" name="url" value=""></textarea>
<button
class="btn btn-primary send-button"
id="submit"
type="submit"
value="SEND">
<span class="send-text">SEND</span>
</button>
</form>
<?php
echo "<table border='1'> <tr/><td width='30%'>Title: $title</td>". "<td width='30%'>Description: $description</td>"."<td width='30%'>Keywords: $keywords</td></tr></table>";
?>
I am trying to fetch meta of a website but I want to use array for multiple pages
If you specified multiple URLs in your textarea - perhaps each one on a separate line - then you could split that value into an array and loop.
So something like this at the top of your PHP code:
$urls = [];
if (!empty($_POST['url'])) {
$urls = array_filter(array_map('trim', explode(PHP_EOL, $_POST['url'])));
}
$results = [];
foreach ($urls as $url) {
// ... then your code as before
$results[$url] = [
'title' => $title,
'description' => $description,
'keywords' => $keywords,
];
}
Then a display loop at the bottom
if (!empty($results)) {
echo "<table border='1'>";
foreach ($results as $url => $result) {
echo "<tr>";
echo "<td width='30%'>Title: " . htmlspecialchars($result['title']) . "</td>"
echo "<td width='30%'>Description: " . htmlspecialchars($result['description']) . "</td>";
echo "<td width='30%'>Keywords: " . htmlspecialchars($result['keywords']) . "</td>";
echo "</tr>";
}
echo "</table>";
}

php multidimensional array to string or table

how can I output this array into html table?
for each row I would like to output it like this, within the foreach;
echo "<td>".$lat."</td><td>".$long."</td>";
as per example on https://developer.here.com/documentation/routing-waypoints/topics/quick-start-simple-car.html
I have tried the code
$api_url = "https://wse.api.here.com/2/findsequence.json?start=Berlin-Main-Station;52.52282,13.37011&destination1=East-Side-Gallery;52.50341,13.44429&destination2=Olympiastadion;52.51293,13.24021&end=HERE-Berlin-Campus;52.53066,13.38511&mode=fastest;car&app_id=ID&app_code=CODE";
$api_response = file_get_contents($api_url);
$api_response_decoded = json_decode($api_response, true);
foreach($api_response_decoded as $api_response_decoded_row){
print_r($api_response_decoded_row[0][waypoints]);
}
and also tried
print_r($api_response_decoded_row[0][waypoints][id]);
and also tried
echo($api_response_decoded_row[0][waypoints][id]);
and also tried
implode($api_response_decoded_row[0][waypoints][id]);
Here's one way you could do it if the comments didn't already help you enough.
foreach($api_response_decoded as $api_response_decoded_rows){
foreach ($api_response_decoded_rows[0]['waypoints'] as $waypoint) {
$html = '
<td>'.$waypoint['lat'].'</td>
<td>'.$waypoint['lng'].'</td>
';
echo $html;
}
}
Thanks to commenters and answerers. In case it helps someone else, full working code is therefore;
$api_url = "https://wse.api.here.com/2/findsequence.json?start=Berlin-Main-Station;52.52282,13.37011&destination1=East-Side-Gallery;52.50341,13.44429&destination2=Olympiastadion;52.51293,13.24021&end=HERE-Berlin-Campus;52.53066,13.38511&mode=fastest;car&app_id=ID&app_code=CODE";
$api_response = file_get_contents($api_url);
$api_response_decoded = json_decode($api_response, true);
echo "<table>";
foreach($api_response_decoded as $api_response_decoded_rows){
foreach ($api_response_decoded_rows[0]['waypoints'] as $waypoint) {
$html = '<tr><td>'.$waypoint['sequence'].'</td><td>'.$waypoint['id'].'</td><td>'.$waypoint['lat'].'</td><td>'.$waypoint['lng'].'</td></tr>';
echo $html;
}
}
echo "</table>";

Iterating through an array and returning first 10 results

So I am trying to iterate through what appears to be json feed, I am using the following code to get all the array results, however, how do I return specific items, lets say the first 6 or 10 ?
<?php
$current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
$headers = array('Content-Type: application/json');
$url = 'https://weedmaps.com/api/web/v1/listings/green-valley-medicinal/menu?show_unpublished=false&type=dispensary';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
$menu_data = json_decode($result, true);
foreach($menu_data['categories'] as $menu_item){
foreach ($menu_item['items'] as $item) {
echo '<article class="col-sm-6 col-md-4">';
echo isset($item['image_url']) ? '<img class="media-object menu-item-photo" height="120" width="120" src="'.$item['image_url'].'">' : '<img class="media-object menu-item-photo" height="120" src="images/mmjicon.png">';
echo '<h2>'.$item['name'].'</h2>';
echo '<p>'.$item['body'].'</p>';
echo '</article>';
}
}
?>
Any help would be greatly appreciated. Cheers!
There are a variety of ways you could do this.
Keeping your foreach loop, add a count, increment it, and break the loop once it reaches 10.
$count = 0;
foreach(...) {
...
if (++$count >= 10) break;
}
If you do not have control over the number of data is being retrieved, you can use a $counter to your foreach.
$your_limit = 6;
$counter = 0;
foreach($menu_data['categories'] as $menu_item){
if ( ++$counter > $your_limit ){
break;
}
foreach ($menu_item['items'] as $item) {
echo '<article class="col-sm-6 col-md-4">';
echo isset($item['image_url']) ? '<img class="media-object menu-item-photo" height="120" width="120" src="'.$item['image_url'].'">' : '<img class="media-object menu-item-photo" height="120" src="images/mmjicon.png">';
echo '<h2>'.$item['name'].'</h2>';
echo '<p>'.$item['body'].'</p>';
echo '</article>';
}
}

What makes this jsessionid shows up on this PHP-code result?

I want to do parsing on this site: CiteSeerx Result.
I tried this:
<?php
include('simple_html_dom.php');
$url = 'http://citeseerx.ist.psu.edu/search?q=mean&t=doc&sort=rlv&start=0';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$curl_scraped_page = curl_exec($ch);
$html = new simple_html_dom();
$html->load($curl_scraped_page);
foreach ($html->find('div.result h3') as $title) {
echo $title->plaintext . '<br/>';
}
echo '---<br>';
foreach ($html->find('div.result h3 a') as $link) {
echo '\'http://citeseeerx.ist.psu.edu' . $link->href . '<br>';
}
echo '---<br>';
foreach ($html->find('div.pubinfo') as $info){
echo $info->innertext. '<br>';
}
echo '---<br>';
foreach ($html->find('div.snippet') as $snippet){
echo $snippet->innertext. '<br>';
}
?>
It works and gives me what I want, it's just that, this jsessionid=... shows up on every single line of the $link results.
What do I do to make it disappear? I googled for addressing this problem, but all I find is the way to solve it with Java, not PHP.
Thanks.
<a class="remove doc_details" href="/viewdoc/summary;jsessionid=103B4C6E9ADA3C8B17DD64BD57238F9D?doi=10.1.1.160.3832">
because the href in the tag includes the jsession id part :)

Categories