PHP List items in json data in a table - php

I am doing some requests using php i am getting this json data from the url i am requesting from and i need to list the name and tag category of each different set of brackets or item out in html how would i go about this see my code below
<?php
$query = $_POST['query'];
$cSession = curl_init();
curl_setopt($cSession,CURLOPT_URL,"https://api.spiget.org/v2/search/resources/" + $query);
curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
curl_setopt($cSession,CURLOPT_HEADER, false);
$result = curl_exec($cSession);
curl_close($cSession);
$json = json_decode($result);
foreach ($json['items'] as $data)
{
echo "<h3>". $json['name']."</h3>";
echo "<h4>". $json['tag']."</h3>";
echo "\n";
echo "\n";
echo "\n";
};?>
JSON DATA
Warning: A non-numeric value encountered in C:\xampp\htdocs\request.php on line 7
Warning: A non-numeric value encountered in C:\xampp\htdocs\request.php on line 7
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\request.php on line 14
Those are the errors i get when the file is run

You define in your json loop as $data so you need to use it in displaying
<?php
$query = $_POST['query'];
$cSession = curl_init();
curl_setopt($cSession,CURLOPT_URL,"https://api.spiget.org/v2/search/resources/" + $query);
curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
curl_setopt($cSession,CURLOPT_HEADER, false);
$result = curl_exec($cSession);
curl_close($cSession);
$json = json_decode($result);
foreach ($json['items'] as $data)
{
echo "<h3>". $data['name']."</h3>";
echo "<h4>". $data['tag']."</h3>";
echo "\n";
echo "\n";
echo "\n";
};?>

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>

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

Loop JSON String response in PHP Foreach

I'm trying to print values of a JSON response in PHP. Inside the contents are:
data
local
acao
detalhes
Codes:
<?php
header('Content-type: text/html; charset=UTF-8');
$url = "http://developers.agenciaideias.com.br/correios/rastreamento/json/RJ290474594CN";
$c_url = file_get_contents($url);
$c_url = utf8_encode($c_url);
$results = json_decode($c_url);
echo $c_url;
?>
I've tried using foreach but wasn't successful in implementing them in said JSON response.
Here is a JSON String Example:
[{"data":"07\/12\/2014 11:19","local":"CHINA - CHINA\/CN","acao":"postado","detalhes":"-"},{"data":"09\/12\/2014 12:03","local":"CHINA - CHINA\/CN","acao":"encaminhado","detalhes":"Em tr\u00e2nsito para Unidade de Tratamento Internacional - BRASIL\/BR"},{"data":"29\/12\/2014 12:34","local":"UNIDADE TRAT INTERNACIONAL PARANA - Curitiba\/PR","acao":"conferido","detalhes":"Recebido\/Brasil "}]
If you just want to print values just print them accordingly using foreach. After getting the response, use json_decode(). That ut8f_encode() is superfluous.
$url = "http://developers.agenciaideias.com.br/correios/rastreamento/json/RJ290474594CN";
$data = json_decode(file_get_contents($url), true);
foreach($data as $values) {
echo $values['data'] . '<br/>';
echo $values['local'] . '<br/>';
echo $values['acao'] . '<br/>';
echo $values['detalhes'] . '<br/>';
}
Sample Output
Or:
$url = "http://developers.agenciaideias.com.br/correios/rastreamento/json/RJ290474594CN";
$data = json_decode(file_get_contents($url), true);
foreach($data as $values) {
foreach($values as $key => $value) {
echo "{$key}: $value <br/>";
}
echo '<hr/>';
}

How to show the information from the link without leaving the site? PHP

I got the site fully working and returning the information from the rss feed since the it return with website link how can i display the information from the link instead of redirect the user back to the original site?
<?php
$query = 'http://query.yahooapis.com/v1/public/yql?q=Select%20*%20from%20rss%20where%20url%3D%22http%3A%2F%2Fnestor.sunderland.ac.uk%2F~bf71wx%2FphpTest%2Fjquery.mobile-1.0.1%2520-%2520%25E8%25A4%2587%25E8%25A3%25BD%2Fjquery.mobile-1.0.1%2Fdemos%2Fdocs%2Frss%2FNews.xml%22%20&diagnostics=true';
$xml = simplexml_load_file($query);
//var_dump($xml);
echo '<h2>World of Tank News</h2>';
//iterate over query result set
$results = $xml->results;
foreach ($results->item as $r){
echo $r->title . "<br />";
echo "" . $r->link . "<br /><br />";
echo 'Publish Date - ';
}
?>
use curl to read the info from link and publish it e.g.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $file);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $_SERVER['REQUEST_URI']);
$result = curl_exec($ch);
curl_close($ch);
no need. you can add this code in your prog e.g.
<?php
$query = 'http://query.yahooapis.com/v1/public/yql?q=Select%20*%20from%20rss%20where%20url%3D%22http%3A%2F%2Fnestor.sunderland.ac.uk%2F~bf71wx%2FphpTest%2Fjquery.mobile-1.0.1%2520-%2520%25E8%25A4%2587%25E8%25A3%25BD%2Fjquery.mobile-1.0.1%2Fdemos%2Fdocs%2Frss%2FNews.xml%22%20&diagnostics=true';
$xml = simplexml_load_file($query);
//var_dump($xml);
echo '<h2>World of Tank News</h2>';
//iterate over query result set
$results = $xml->results;
foreach ($results->item as $r){
echo $r->title . "<br />";
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$r->link);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
// echo "" . $r->link . "<br /><br />";
// echo 'Publish Date - ';
}
?>

Twitter Trends PHP

I am trying to use http://api.twitter.com/1/trends/current.json?exclude=hashtags however I am having some trouble.
So, I'm trying to use:
<?php
$init = 'http://api.twitter.com/1/trends/current.json?exclude=hashtags';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$init);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result, true);
foreach ($obj[0]['trends'] as $trend) {
print $trend['query'];
echo "<br>";
print $trend['name'];
echo "<hr>";
}
?>
And I am getting this Error:
Notice: Undefined offset: 0 in \index.php on line 11
Warning: Invalid argument supplied for foreach() \index.php on line 11
You read the JSON wrong. You need to do something like the following:
foreach ($obj['trends']['2011-02-23 18:00:00'] as $trend) {
print $trend['query'];
echo "<br>";
print $trend['name'];
echo "<hr>";
}
If I am not wrong
$obj = json_decode($result, true);
would produce an array and not an object. secondly using the twitter api is as simple as:
<?php
function get_trends($woeid){
return json_decode(file_get_contents("http://api.twitter.com/1/trends/".$woeid.".json?exclude=hashtags", true), false);
}
$data = get_trends(23424848); //23424848 is woeid for India...
$trends = $data[0]->trends;
echo "<ul>";
if(!empty($trends)){
foreach($trends as $trend){
echo '<li>'.$trend->name.'</li>';
}
}
echo "</ul>";
?>

Categories