php foreach loop with 2 variables in json_decode - php

In a foreach loop i am trying to make a link with data from two variables. Like this:
$baseAttachementUrl = str_replace($rowAttachTags, $rowAttachVals, $getAttachmentURL);
foreach ($attachments as $attachment){
$rowAttachTags = array('{{ROWID}}', '{{SHEETID}}','{{ATTACHMENTID}}');
$rowAttachVals = array($addRowsObj->result[0]->id, $theSheet->id, $attachment->id);
$getAttachmentURL = $baseAttachementUrl;
$getNEWAttachmentURL = str_replace($rowAttachTags, $rowAttachVals, $getAttachmentURL);
$curlSession = curl_init($getNEWAttachmentURL);
curl_setopt($curlSession, CURLOPT_HTTPHEADER, $header);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, TRUE);
getAttachmentResponse = curl_exec($curlSession);
$getFileObj = array(json_decode($getAttachmentResponse, true));
foreach ($getFileObj as $fileObj){
echo "<a href='". $fileObj['url']."'>". $fileObj['name']."</br></a>";
}
}
The first row in the table works. 2 files comes out with the right url. but in all subsequent rows the last file from the first row comes out.

A couple of problems here that you are not being too specific about. However I will try my best to respond.
First of all, we dont know how the results of $attachments or $getFileObj look like. We are assuming that the part of your question that says "returns stdClas..." is a portion of the results of $getFileObj.
Another problem is that we dont know where you're getting $getAttachmentURL from.. Is this a variable statically set, or is it a variable that comes as a result of $attachments?
Taking those problems into consideration I believe what you're trying to do is to first get the all the attachments and store them into $attachments. Then, you want to get each attachment url from you intial result and iterate through each to get your fileURL. I would do the following:
<?php
curl_setopt($curlSession, CURLOPT_HTTPHEADER, $header);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, TRUE);
$getAttachmentsResponse = curl_exec($curlSession);
// Assign response to variable
$attachments = json_decode($getAttachmentsResponse);
foreach ($attachments as $attachment) {
$getAttachmentURL = $attachment->attachment_URL;
$curlSession = curl_init($getAttachmentURL);
curl_setopt($curlSession, CURLOPT_HTTPHEADER, $header);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, TRUE);
$getAttachmentResponse = curl_exec($curlSession);
// Assign response to variable
$getFileObj = json_decode($getAttachmentResponse);
echo "<td>";
echo "<a href='" . $getFileObj->url . "'>" . $attachment->name . "</br></a>";
echo "</td>";
}

Try....
// ... curl setup
$attach = json_decode($getAttachmentsResponse);
// ... curl setup two
$file = json_decode($getAttachmentResponse);
$joinedattachment[ 'attach' ] = $attachone;
$joinedattachment[ 'file' ] = $file;
$attachments[] = $joinedattachment;
$iCountAttachments = count( $attachments );
echo "<td>";
for( $i = 0; $i < $iCountAttachments; ++$i )
{
echo "<a href='". $attachments[ $i ][ 'file' ]."'>". $attachments[ $i ][ 'attach' ] ."</br></a>";
}
echo "</td>";

Related

How to parse plaintext data from a particular url with PHP?

I am using this code to pull data to my site from an external source, and am wondering how I would parse this using PHP.
include(app_path().'/Includes/simple_html_dom.php');
$html = file_get_html("http://www.teamsideline.com/sites/parkfun/schedule/153461/Adult-Outdoor-Soccer-Mens-Competitive", NULL, NULL, NULL, NULL);
$data = array();
foreach($html->find("tbody tr") as $tr){
$row = array();
foreach($tr->find("td") as $td){
/* enter code here */
$row[] = $td->plaintext;
}
$data[] = $row;
}
I am trying to extract the standings data in particular, and recreate the standings table on my page with the data from this site. How can I achieve this?
Seems like the website doesn't allow file_get_html(). Atleast for me it's not working.
Anyway, you could use cUrl to get the html string and then parse that string using str_get_html().
To display the table on your website, simply echo the found data like this:
$url = 'http://www.teamsideline.com/sites/parkfun/schedule/153461/Adult-Outdoor-Soccer-Mens-Competitive';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
$result = curl_exec($curl);
$html = str_get_html($result);
$data = "";
$data .= "<table width='100%'>";
foreach($html->find("tbody tr") as $tr){
$data .= "<tr>";
foreach($tr->find("td") as $td){
$data .= "<td style='border: 1px black solid'>";
$data .= $td->plaintext;
$data .= "</td>";
}
$data .= "</tr>";
}
$data .= "</table>";
echo $data;

CSE Google Custom Page api show 50 results PHP?

I'm trying to get the first 50 results of the Google CSE API with the following PHP code.
The problem is that it combines the two pages sow the results are getting messed up like the first position is the one of the first page and the second position is the second of the second page and so on. Can someone tell me what I am doing wrong here?
What I actually want to do is get the first 50 results in a array, but the code below gives me mixed results.
$apiKey = "theapikey";
$query = "news";
for ($i = 1; $i <= 5; $i++) {
$ch = curl_init();
$request = "https://www.googleapis.com/customsearch/v1?q=" . urlencode( "$query" ) . "&cx=013594553343653397533:q-qkkaltmay" ."&key=" . $apiKey . "&start=" . $i;
curl_setopt($ch, CURLOPT_URL, $request);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$output = curl_exec($ch);
$output = json_decode($output);
foreach( $output->items as $result ) {
$url = $result->link;
${"items" . $i}[] = $url;
}
}
echo json_encode($items1);
It looks like you are adding each set of 10 results into a separate array, so $items1 has the first 10 results, $items2 has the next 10, etc. If you want all 50 results in a single array, there is no need to use an index in the array's name.
Also, the "start" parameter is the number of the result you want, not the number of the result set - so you want the first query to start at 1, the second to start at 11, the third at 21, etc.
You may also want to check that there is something in the result before adding it to your array.
I might do something more like so:
$apiKey = "theapikey";
$query = "news";
$items = array();
for ($i = 1; $i <= 5; $i++) {
$ch = curl_init();
$request = "https://www.googleapis.com/customsearch/v1?" .
"q=" . urlencode( "$query" ) .
"&cx=013594553343653397533:q-qkkaltmay" .
"&key=" . $apiKey .
"&start=" . ( ($i - 1)*10 + 1 );
curl_setopt($ch, CURLOPT_URL, $request);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$output = curl_exec($ch);
$output = json_decode($output);
foreach( $output->items as $result ) {
if ($url = $result->link && trim($url)) $items[] = $url;
}
}
echo json_encode($items);
Finally, a couple caveats:
There is an existing question about whether this JSON api is deprecated and possibly going away.
Each query for the next 10 results counts against your quota. If you are worried about running out of queries each month, or if you are paying for quota increases, you may want to consider only retrieving what you need.

How to get all comments from a Youtube video

Firstly, I looked all of other title. All of them out of date. I mean, they are use old api.
I write a code to list all comments with their nextPageToken
<?php
$url = "SE0wDh_pILk"; // Youtube video ID
$ytkey = "IzaSyCaRXmJ9XDC4XucAZCzXx7hisCtYEH0mNs"; //"IzaSyBuu-rnbmPAj1DjR6WmyxGmpmQKz8aTXbw" Your api key
$nextPage = ""; // Next Page Token for get comments of next Page.
//$i =0; // DO NOT CHANGE
for ($i = 0; $i < 5; $i++) {
$str = file_get_contents("https://www.googleapis.com/youtube/v3/commentThreads?key=" . "$ytkey" . "&textFormat=plainText&part=snippet&videoId=" . "$url" . "&maxResults=100&nextPagetoken=" . "$nextPage");
$json = json_decode($str, true); // decode the JSON into an associative array
//echo '<pre>' . print_r($json, true) . '</pre>'; // Print json data as array structer ..
echo "$i - " . "Next Page Token : " . $json['nextPageToken']; // Take the next Page Token for get next 100 comment...
echo "<hr>"; // Divider
$nextPage = $json['nextPageToken']; // Take token for next query
// print comments.
foreach ($json['items'] as $val) { // Loop for list comments...
$author = $val['snippet']['topLevelComment']['snippet']['authorDisplayName']; //Get Comment Author Name.
//$author_url = $val['snippet']['topLevelComment']['snippet']['authorChannelUrl']; //Get Comment Author URL.
//$author_thumbnail_url = $val['snippet']['topLevelComment']['snippet']['authorProfileImageUrl']; //Get Comment Author Thumbnail URL.
$comment = $val['snippet']['topLevelComment']['snippet']['textDisplay']; //Get Comment Content.
echo "<span style='color:red';>" . "$author" . "</span>" . " --> " . "$comment"; // Author and comment
echo "<hr>"; // Divider
}
}
echo "Process over. ";
?>
I learn how to parse json and how to show them on php from stackoverflow.
Now, there is no problem with taking nextPageTokens. But I can't get comments.
When I run the script, It returns different nextPageToken but comments are same, they come from the first page.
I try to add enough comment line.
Sorry I can't color the php codes.
You are calling commentThreads with the parameter &nextPagetoken=.
The correct parameter to use is &pageToken=.
Here is a recursive,bare bones function to return all comments from a video
public function getAllComments($videoId,$pageToken=null,$maxResults){
$url = "https://www.googleapis.com/youtube/v3/commentThreads";
static $all =[];
$params =[
'key' => 'your-key',
'part' => 'snippet',
'maxResults' => $maxResults,
'videoId' => $videoId,
'pageToken' => $pageToken
];
$call = $url.'?'.http_build_query($params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $call);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
$data = NULL;
$data = json_decode($output,true);
$all[] = $data;
if(isset($data['nextPageToken'])){
if($data['nextPageToken'] != NULL ){
$pageToken = $data['nextPageToken'];
getAllComments($videoId,$pageToken,$maxResults);
}
}
curl_close($ch);
return $all;
}
Finally I found a site that does what I want to do.
If you have to collect all comments of a video and take one of them randomly for lottery etc. , use these sites ->
https://www.randomcommentpicker.com
http://commentpicker.com/youtube.html

Illegal string offset 'date'

I am trying to upgrade a friend's Wordpress site to the latest versions of Wordpress and PHP.
All is working fine except for a scrolling news ticker he uses on his homepage that errors out with "Illegal string offset 'date'", and no news is shown.
This is the script:
<?php
$xmlOption = get_option('xmlFeed');
if (!isset($xmlOption)) {
$buildURL = "https://wordpress.org/news/feed/";
$request = curl_init();
curl_setopt($request, CURLOPT_URL, $buildURL);
curl_setopt($request, CURLOPT_HEADER, false);
curl_setopt($request, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($request);
curl_close($request);
$xml = new SimpleXMLElement($result);
$channel = $xml->channel;
delete_option('xmlFeed');
$otion = array(
'xml' => $channel,
'date' => date('y-m-d')
);
add_option('xmlFeed', $option);
}
if ($xmlOption['date'] == date('y-m-d')) {
$channel = $xmlOption['xml'];
} else {
$buildURL = "https://wordpress.org/news/feed/";
$request = curl_init();
curl_setopt($request, CURLOPT_URL, $buildURL);
curl_setopt($request, CURLOPT_HEADER, false);
curl_setopt($request, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($request);
curl_close($request);
$xml = new SimpleXMLElement($result);
$channel = $xml->channel;
delete_option('xmlFeed');
$otion = array(
'xml' => $channel,
'date' => date('y-m-d')
);
add_option('xmlFeed', $option);
}
$i = 0;
while ($i <= 5) {
echo "<li><a href='" . $channel->item->$i->link . "' target='_blank'>" . $channel->item->$i->title . "</a></li>";
$i++;
}
?>
I noticed the use of $otion two times, which i thought was maybe a typo. But when i changed that to $option the rest of the page was not parsed, so I guess that isn't the problem.
As I am not a coder and i pulled my hairs out for 2 nights now.
Time to get some help before i have none left.
Anyone can help me with this one?
It is not a real answer to my question, but I found another script that, with some small changes, works perfectly. So I'm happy.
<?php
$rss = new DOMDocument();
$rss->load('http://wordpress.org/news/feed/');
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
);
array_push($feed, $item);
}
$limit = 5;
for($x=0;$x<$limit;$x++) {
$title = str_replace(' & ', ' & ', $feed[$x]['title']);
$link = $feed[$x]['link'];
echo '<li>'.$title.'</li>';
}
?>
It is smaller and cleaner.
Thanks for your help #Marcus

Issues with decoding two JSON feed sources and display with PHP/HTML

I am using two JSON feed sources and PHP to display a real estate property slideshow with agents on a website. The code was working prior to the feed provider making changes to where they store property and agent images. I have made the necessary adjustments for the images, but the feed data is not working now. I have contacted the feed providers about the issue, but they say the problem is on my end. No changes beyond the image URLs were made, so I am unsure where the issue may be. I am new to JSON, so I might be missing something. I have included the full script below. Here are the two JSON feed URLs: http://century21.ca/FeaturedDataHandler.c?DataType=4&EntityType=2&EntityID=2119 and http://century21.ca/FeaturedDataHandler.c?DataType=3&AgentID=27830&RotationType=1. The first URL grabs all of the agents and the second grabs a single agent's properties. The AgentID value is sourced from the JSON feed URL dynamically.
class Core
{
private $base_url;
private $property_image_url;
private $agent_id;
private $request_agent_properties_url;
private $request_all_agents_url;
private function formatJSON($json)
{
$from = array('Props:', 'Success:', 'Address:', ',Price:', 'PicTicks:', ',Image:', 'Link:', 'MissingImage:', 'ShowingCount:', 'ShowcaseHD:', 'ListingStatusCode:', 'Bedrooms:', 'Bathrooms:', 'IsSold:', 'ShowSoldPrice:', 'SqFootage:', 'YearBuilt:', 'Style:', 'PriceTypeDesc:');
$to = array('"Props":', '"Success":', '"Address":', ',"Price":', '"PicTicks":', ',"Image":', '"Link":', '"MissingImage":', '"ShowingCount":', '"ShowcaseHD":', '"ListingStatusCode":', '"Bedrooms":', '"Bathrooms":', '"IsSold":', '"ShowSoldPrice":', '"SqFootage":', '"YearBuilt":', '"Style":', '"PriceTypeDesc":' );
return str_ireplace($from, $to, $json); //returns the clean JSON
}
function __construct($agent=false)
{
$this->base_url = 'http://www.century21.ca';
$this->property_image_url = 'http://images.century21.ca';
$this->agent_id = ($agent ? $agent : false);
$this->request_all_agents_url =
$this->base_url.'/FeaturedDataHandler.c?DataType=4&EntityType=3&EntityID=3454';
$this->request_agent_properties_url =
$this->base_url.'/FeaturedDataHandler.c?DataType=3'.'&AgentID='.$this->agent_id.'&RotationType=1';
}
/**
* getSlides()
*/
function getSlides()
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->request_all_agents_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$response = curl_exec($ch);
curl_close($ch);
if (empty($response))
return false;
else
$agents = $this->decode_json_string($response);
// Loop Agents And Look For Requested ID
foreach ($agents as $agent)
{
if (($this->agent_id != false) && (isset($agent['WTLUserID'])) && ($agent['WTLUserID'] != $this->agent_id))
{
continue; // You have specified a
}
$properties = $this->getProperties($agent['WTLUserID']);
$this->print_property_details($properties, $agent);
}
}
/**
* getProperties()
*/
function getProperties($agent_id)
{
$url = $this->base_url.'/FeaturedDataHandler.c?DataType=3'.'&AgentID='.$agent_id.'&RotationType=1';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$response = curl_exec($ch);
curl_close($ch);
$json = json_decode($response);
if (empty($response))
die('No response 2'); //return false;
else
$json = $this->formatJSON($this->decode_json_string($response));
var_dump($json);
die();
// return $json;
}
/**
* print_property_details()
*/
function print_property_details($properties, $agent, $html='')
{
$BASE_URL = $this->base_url;
$PROPERTY_IMAGE_URL = $this->property_image_url;
foreach ($properties as $property)
{
$img = $property['Image'];
// $img = ($property['Image'] ? $property['Image'] : "some url to a dummy image here")
if($property['ListingStatusCode'] != 'SOLD'){
$address = $property['Address'];
$shortaddr = substr($address, 0, -12);
$html .= "<div class='listings'>";
$html .= "<div class='property-image'>";
$html .= "<img src='". $PROPERTY_IMAGE_URL ."' width='449' height='337' alt='' />";
$html .= "</div>";
$html .= "<div class='property-info'>";
$html .= "<span class='property-price'>". $property['Price'] ."</span>";
$html .= "<span class='property-street'>". $shortaddr ."</span>";
$html .= "</div>";
$html .= "<div class='agency'>";
$html .= "<div class='agent'>";
$html .= "<img src='". $agent['PhotoUrl']. "' class='agent-image' width='320' height='240' />";
$html .= "<span class='agent-name'><b>Agent:</b>". $agent['DisplayName'] ."</span>";
$html .= "</div>";
$html .= "</div>";
$html .= "</div>";
}
}
echo $html;
}
function decode_json_string($json)
{
// Strip out junk
$strip = array("{\"Agents\": [","{Props: ",",Success:true}",",\"Success\":true","\r","\n","[{","}]");
$json = str_replace($strip,"",$json);
// Instantiate array
$json_array = array();
foreach (explode("},{",$json) as $row)
{
/// Remove commas and colons between quotes
if (preg_match_all('/"([^\\"]+)"/', $row, $match)) {
foreach ($match as $m)
{
$row = str_replace($m,str_replace(",","|comma|",$m),$row);
$row = str_replace($m,str_replace(":","|colon|",$m),$row);
}
}
// Instantiate / clear array
$array = array();
foreach (explode(',',$row) as $pair)
{
$var = explode(":",$pair);
// Add commas and colons back
$val = str_replace("|colon|",":",$var[1]);
$val = str_replace("|comma|",",",$val);
$val = trim($val,'"');
$val = trim($val);
$key = trim($var[0]);
$key = trim($key,'{');
$key = trim($key,'}');
$array[$key] = $val;
}
// Add to array
$json_array[] = $array;
}
return $json_array;
}
}
Try this code to fix the JSON:
$url = 'http://century21.ca/FeaturedDataHandler.c?DataType=3&AgentID=27830&RotationType=1';
$invalid_json = file_get_contents($url);
$json = preg_replace("/([{,])([a-zA-Z][^: ]+):/", "$1\"$2\":", $invalid_json);
var_dump($json);
All your keys need to be double-quoted
JSON on the second URL is not a valid JSON, that's why you're not getting the reults, as PHP unable to decode that feed.
I tried to process it, and get this error
Error: Parse error on line 1:
{Props: [{Address:"28
-^
Expecting 'STRING', '}'
Feed image for first URL
and here is view of 2nd URL's feed
as per error for second feed, all the keys should be wrapped within " as these are strings rather than CONSTANTS.
e.g.
Props should be "Props" and all other too.
EDIT
You need to update your functionand add this one(formatJSON($json)) to your class
// Update this function, just need to update last line of function
function getProperties($agent_id)
{
$url = $this->base_url.'/FeaturedDataHandler.c?DataType=3'.'&AgentID='.$agent_id.'&RotationType=1';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$response = curl_exec($ch);
curl_close($ch);
$json = json_decode($response);
if (empty($response))
die('No response 2'); //return false;
else
return $this->formatJSON($this->decode_json_string($response)); //this one only need to be updated.
}
//add this function to class. This will format json
private function formatJSON($json){
$from= array('Props:', 'Success:', 'Address:', ',Price:', 'PicTicks:', ',Image:', 'Link:', 'MissingImage:', 'ShowingCount:', 'ShowcaseHD:', 'ListingStatusCode:', 'Bedrooms:', 'Bathrooms:', 'IsSold:', 'ShowSoldPrice:', 'SqFootage:', 'YearBuilt:', 'Style:', 'PriceTypeDesc:');
$to = array('"Props":', '"Success":', '"Address":', ',"Price":', '"PicTicks":', ',"Image":', '"Link":', '"MissingImage":', '"ShowingCount":', '"ShowcaseHD":', '"ListingStatusCode":', '"Bedrooms":', '"Bathrooms":', '"IsSold":', '"ShowSoldPrice":', '"SqFootage":', '"YearBuilt":', '"Style":', '"PriceTypeDesc":' );
return str_ireplace($from, $to, $json); //returns the clean JSON
}
EDIT
I've tested that function, and it's working fine, may be there is something wrong with your function decode_json_string($json)
I've taken unclean json from second URL, and cleaning it here, and putting that cleaned json in json editor to check either it's working or not HERE

Categories