Remove array from JSON decode - php

Here's the function I'm using to grab and process a JSON input:
<?php
$json = "http://pastebin.com/raw.php?i=ihAapq30";
$cache_lastfm = 'BLAHBLAHDIR/'.sha1($json).'.json';
if(file_exists($cache_lastfm) && filemtime($cache_lastfm) > time() - 1000){
// if a cache file newer than 1000 seconds exists, use it
$data = json_decode(file_get_contents($cache_lastfm), true);
} else {
$data = json_decode(file_get_contents($json), true);
file_put_contents($cache_lastfm,json_encode($data));
}
$data = $data['recenttracks'];
foreach ($data['track'] as $track) {
$artist = $track['artist']['#text'];
$title = $track['name'];
$url = $track['url'];
echo '<li>', $artist, ' - ', $title, '</li>'; }
?>
It works perfectly.. my question is, how can I remove only the "entry" that has the:
"#attr":{
"nowplaying":"true"
}
... "attribute"? Check the pastebin page to understand what I mean :)

Please try this:
<?php
$data = $data['recenttracks'];
$tracks=$data['track'];
foreach ($tracks as $index=>$track) {
if (isset($track['#attr'])) {
unset($tracks[$index]);
}
}
foreach ($tracks as $track) {
$artist = $track['artist']['#text'];
$title = $track['name'];
$url = $track['url'];
echo '<li>', $artist, ' - ', $title, '</li>';
}
?>

Related

Creating pages from a csv file

I've created a page that grabs data from a CSV (http://liamjken.com/aim-parse/aim-websites-new.csv) and displays it on this page http://www.liamjken.com/aim-parse/parse.php?17
?17 references the row in the csv file. so if I change that to ?10 it pulls the info from a different row.
What I would like to do instead of using the row number is use the $vin_num value. so if I put ?1FMCU9GD9KUC40413 at the end of the URL it would display the row that contains that Number.
here is the code I have currently, its basically cobbled together from multiple different trends I found so if you notice other potential problems id be happy to hear about them.
<?php
$qstring = $_SERVER['QUERY_STRING'];
$row = $qstring; // The row that will be returned.
$data = get_row('aim-websites-new.csv', $row);
'<pre>'.print_r($data).'</pre>';
function get_row($csv, $row) {
$handle = fopen("$csv", 'r');
$counter = 0;
$result = '';
while ( ($data = fgetcsv($handle)) !== FALSE ) {
$counter++;
if ( $row == $counter ) {
$vin_num="$data[12]";
$model="$data[10]";
$make="$data[9]";
$year="$data[8]";
ob_start();
?>
<h1>VIN: <?php echo $vin_num; ?></h1>
<h1>Year: <?php echo $year; ?></h1>
<h1>Make: <?php echo $make; ?></h1>
<h1>Model: <?php echo $model; ?></h1>
<?php
$output = ob_get_clean();
ob_flush();
return $output;
}
}
}
?>
<?php
function extract_data($file)
{
$raw = file($file); // file() puts each line of file as string in array
$keys = str_getcsv(array_shift($raw)); // extract the first line and convert into an array
// Look through the rest of the lines and combine them with the header
$data = [];
foreach ($raw as $line) {
$row = str_getcsv($line);
$data[] = array_combine($keys, $row);
}
return $data;
}
function get_record($data, $vin)
{
foreach ($data as $record) {
if ($record['VIN'] === $vin)
return $record;
}
return null;
}
$data = extract_data('aim-websites-new.csv');
$vin = $_SERVER['QUERY_STRING'];
if (empty($vin)) {
echo '<h1>No VIN provided</h1>';
exit;
}
$record = get_record($data, $vin);
if ($record === null) {
echo '<h1>No record found</h1>';
exit;
}
echo '<h1>' . $record['VIN'] . '</h1>';
echo '<h1>' . $record['Year'] . '</h1>';
echo '<h1>' . $record['Make'] . '</h1>';
echo '<h1>' . $record['Model'] . '</h1>';
echo '<pre>' . print_r($record, true) . '</pre>';
If you don't trust that the records will have valid VINs, you can use the code posted here to validate: How to validate a VIN number?

How can I check If I get empty file_get_html in PHP HTML Dom?

I am getting JSON data through visiting a link using PHP HTML DOM, but sometimes, I get an empty page so I want to know that how can I really check if page is empty so that I can skip it by using continue in for loop
I am checking it through :
if (empty($jsondata))
But I always get TRUE never gets false even if page is returned empty
Here is my code :
<?php
$prefix = $_POST['prefix'];
$start_product = $_POST['start_product'];
$end_product = $_POST['end_product'];
set_time_limit(0);
for ($i=$start_product; $i <= $end_product; $i++) {
include('simple_html_dom.php');
$prefix ="00";
$i= "11";
$jsondata = file_get_html('http://www.ewallpk.com/index.php?controller=search&q=A'.$prefix.$i.'&limit=10&timestamp=1445547668758&ajaxSearch=1&id_lang=1');
if (!empty($jsondata)) {
$data = json_decode($jsondata, true);
$product = file_get_html($data[0]["product_link"]);
$product_name= "";
foreach($product->find('div[id=pb-left-column] h1') as $element) {
$product_name.=$element->innertext . '<br>';
}
$product_name = explode("_", $product_name);
$count = count($product_name);
if ($count < 3) {
$product_name=$product_name[0];
} else {
$product_name = "Error";
}
$product_description= "";
foreach($product->find('div[id=short_description_content]') as $element) {
$product_description.=$element->plaintext . '<br>';
}
$product_price= "";
foreach($product->find('p[class=our_price_display] span') as $element) {
$product_price.=$element->innertext . '<br>';
}
$image_link= "";
foreach($product->find('img[id=bigpic]') as $element) {
$image_link.=$element->src;
}
$content = file_get_contents($image_link);
file_put_contents('item_images/A'.$prefix.$i.'.jpg', $content);
echo "<strong>Product No : </strong> A".$prefix.$i."</br>";
echo "<strong>Product Name : </strong>".$product_name."</br>";
echo "<strong>Product Description : </strong>".$product_description;
echo "<strong>Product Price : </strong>".$product_price."</br></br></br>";
} else {
continue;
}
}
?>
You're probably getting some whitespace in the empty response, so trim it off before testing. You also should be using file_get_contents, since the response is not HTML.
$jsondata = file_get_contents('http://www.ewallpk.com/index.php?controller=search&q=A'.$prefix.$i.'&limit=10&timestamp=1445547668758&ajaxSearch=1&id_lang=1');
$jsondata = trim($jsondata);
if (!empty($jsondata)) {
...
}

Data from JSON to php?

I need help with fetching only attraction data,
i have this php script on my website:
<?php $json_string = 'http://framecreators.nl/efteling/data.php'; $jsondata file_get_content($json_string); $json_o=json_decode(utf8_encode($data)); $attractie = $json_o['Id']['Type']; echo $attractie ?>
and this json data:
http://framecreators.nl/efteling/data.php
I need to convert only a Id and type, ff somebody can help me.
To access the data you're looking for, you'll need to do something like this:
foreach ($json_o['AttractionInfo'] as $a) {
echo $a['Id']; //or whatever you're planning to do with this data
ech0 $a['Type'];
}
<?php
$json_data = file_get_contents('http://framecreators.nl/efteling/data.php');
$data = json_decode($json_data);
$array = [];
foreach($data->AttractionInfo as $item) {
$array['id'][] = $item->Id;
$array['type'][] = $item->Type;
}
echo "<pre>";
print_r($array);
echo "</pre>";
$url = "http://framecreators.nl/efteling/data.php";
$content = file_get_contents($url);
$data = json_decode($content,TRUE);
$array = $data['AttractionInfo'];
foreach($array as $r)
{
echo "ID->".$r['Id'];
echo '';
echo "Type->".$r['Type'];
echo '';
}
$url = "http://framecreators.nl/efteling/data.php";
$content = file_get_contents($url);
$data = json_decode($content,TRUE);
$array = $data['AttractionInfo'];
if(is_array($array))
{
foreach($array as $r)
{
echo $r['Id'];
echo $r['Type'];
}
}

Loop a foreach json loop in another foreach json loop

I'm at a 24 hour hackathon trying to solve this so, excuse if it's a little rushed.
1st for each loop works fine, I'm getting a list of categories from this url
https://dev.xola.com/api/categories
I grab the list with this
$fullurl = "https://dev.xola.com/api/categories";
$string .= file_get_contents($fullurl); // get json content
$json_a = json_decode($string, true); //json decoder
then loop it with this
<?
foreach($json_a as $v)
{?>
echo $v ?}>
Now with the second for each look, I want to grab the items from this url
https://dev.xola.com/api/experiences
that match the category from the last url
so samething
$fullurl = "https://dev.xola.com/api/categories";
$string .= file_get_contents($fullurl); // get json content
$json_b = json_decode($string, true); //json decoder
here's the complete loop I tried
<?
$i=0;
foreach($json_a as $v)
$i++
{?>
echo $v ?
foreach($json_b as $x){?>
if($v==$x):
echo $v
endif;
?>
}?>
This will create a $result array with only the data that had the categories early acquired:
<?php
$categories_url = "https://dev.xola.com/api/categories";
$data = file_get_contents($categories_url);
$categories = json_decode($data, true);
$experiences_url = "https://dev.xola.com/api/experiences";
$data = file_get_contents($experiences_url);
$experiences = json_decode($data, true);
$result = array();
foreach ($experiences['data'] as $experience)
{
if (in_array($experience['category'], $categories))
{
$result[] = $experience;
}
}
print_r($result);
And you can easily read the result with:
foreach ($result as $item)
{
echo $item['category'], "\n";
echo $item['desc'], "\n";
//... other data available ...
}
The data structure of the experiences JSON is not the same as the categories JSON, therefore if($v==$x) will never match. If you want to find all results in experiences with a category from the categories url you can do the following:
<?
$BASE_URL = 'https://dev.xola.com/api/';
$categories = json_decode(file_get_contents($BASE_URL . 'categories'));
$experiences = json_decode(file_get_contents($BASE_URL . 'experiences'));
$matches = array();
foreach( $categories as $category ) {
foreach( $experiences->data as $experience ) {
if( $experience->category === $category ) {
$matches[] = $experience;
}
}
}
?>
<? foreach( $matches as $match ) : ?>
<? echo $match->category; ?><br>
<? endforeach; ?>

First and Second last xml nodes

I only want the first and the second last Area nodes - how would I do that here?
$url = "http://developer.multimap.com/API/geocode/1.2/OA10081917657704697?qs=Byker&countryCode=GB";
$results = simplexml_load_file($url);
foreach($results->Location as $location) {
echo "<hr />";
foreach($location->Address as $address) {
foreach($address->Areas as $areas) {
foreach($areas->Area as $area) {
echo $area;
echo "<br />";
}
}
}
}
Update: If you have those foreach-loops anyway you can simply use:
$url = "http://developer.multimap.com/API/geocode/1.2/OA10081917657704697?qs=Byker&countryCode=GB";
$results = simplexml_load_file($url);
foreach($results->Location as $location) {
foreach($location->Address as $address) {
foreach( $address->Areas as $areas) {
// <-- todo: add test if those two elements exist -->
echo $areas->Area[0], ' - ', $areas->Area[count($areas->Area)-1], "\n";
}
}
}
You can use XPath for this.
<?php
$doc = new SimpleXMLElement('<foo>
<bar>a</bar>
<bar>b</bar>
<bar>c</bar>
<bar>x</bar>
<bar>y</bar>
<bar>z</bar>
</foo>');
$nodes = $doc->xpath('bar[position()=1 or position()=last()-1]');
foreach( $nodes as $n ) {
echo $n, "\n";
}
prints
a
y
see also:
PHP Manual: SimpleXMLElement::xpath()
XPath: predicates
XPath: position()
XPath: last()
Here it is:
<?php
$url = 'http://developer.multimap.com/API/geocode/1.2/OA10081917657704697?qs=Byker&countryCode=GB';
$results = simplexml_load_file($url);
$areas = array();
foreach ($results->Location->Address->Areas->Area as $area)
{
$areas[] = (string) $area;
}
$first = $areas[0];
$second_last = $areas[count($areas)-2];
?>

Categories