PHP JSON Parsing Issue - php

I have this JSON output from a Government API, I need to display it using PHP. The problem is I can't use foreach more then once in a row or it doesn't work. I can't load all the criteria into the first foreach because say the first piece of data ACASS returns 3 results, all the fields after it will be displayed 3 times. Each field could return 1-10 results so there needs to be a system that accounts for variables.
I'm thinking the solution is to put all of the JSON items I need displayed into the first foreach but set them to only display if they're populated. That or use the current coding system I have but account for variable numbers somehow.
Any potential solutions are greatly appreciated.
This is the JSON output... https://api.data.gov/sam/v4/registrations/9606040070000?api_key=WI7nHENlp6QDMnWsb0Nnmzsv1slPDTjNM0XBoKvY
Here's the PHP I'm using...
echo "ACASS ID:".$decoded_results['sam_data']['registration']['qualifications']['acass']['id']."</br>";
foreach($decoded_results['sam_data']['registration']['qualifications']['acass']['answers'] as $acass)
{
echo 'Answer Text:'.$acass['answerText'].'</br>';
echo 'ACASS Section:'.$acass['section'].'</br>';
}
$formerfirm = $decoded_results['sam_data']['registration']['qualifications']['acass']['answers'][2]['FormerFirm'];
echo 'Former Firm ID:'.$formerfirm['id'].'</br>';
echo 'Former Firm Year Established:'.$formerfirm['yearEstablished'].'</br>';
echo 'Former Firm Name:'.$formerfirm['name'].'</br>';
echo 'Former Firm DUNS'.$formerfirm['duns'].'</br>';
I did my best to keep this short and simple question / code wise. In summary the issue is if you look at the JSON the data hierarchy makes a lot of the information display under ACASS/Answers and then the next category. I never know how many responses there will be and I'm not sure how to account for those variables.
I would like to thank everyone on these boards who has guided me as a new member and helped me post cleaner, more concise questions. Also thank you to everyone who has taken their own personal time to help me learn to become a better programmer.

use a tool like http://jsonviewer.stack.hu/ for visualizing your json structure. It helps a lot.
<?php
$url = "https://api.data.gov/sam/v4/registrations/9606040070000?api_key=WI7nHENlp6QDMnWsb0Nnmzsv1slPDTjNM0XBoKvY";
$contents = json_decode(file_get_contents($url));
// echo var_dump($contents);
$sam_data = $contents->sam_data;
// echo var_dump($sam_data);
$registration = $sam_data->registration;
//echo var_dump($registration);
$acass = $contents->sam_data->registration->qualifications->acass;
$id = $acass->id;
echo "id: ". $id . "<br />";
//echo var_dump($acass->answers);
foreach($acass->answers as $answer) {
if(isset($answer->FormerFirm)) {
$formerFirm = $answer->FormerFirm;
echo var_dump($formerFirm);
}
}

Related

Splitting an external array to give different titles

I've been trying to figure out how to split the array and add different titles for each of the separate titles on the page, for each of the different things that this displays. However the most I can manage to do is add a comma between the numbers and words.
I would like to add selling"1st variable price"second variable" etc however I don't quite know how to do anything other than to turn this very confusing looking bunch of letters:
user name and notes 01001000013972583957ecCCany amount-w378- v west
into anything other than this:
0,100,10000,1397258395,7ec,CC,any amount-w378- v west
Also, this is what it looks like in its JSON form:
{"selling":"0","quantity":"100","price":"10000","date":"1397258395","rs_name":"7ec","contact":"CC","notes":"any amount-w378- v west"}
I just want all the information that is in there to displayed like that however I'm not quite sure how to add the titles that is in the JSON data. I also don't have access to the external site to change anything.
A little background: what I am trying to achieve is a price look-up for a game on my website from an external site. I tried to use an iframe but it was terrible; I would rather just manually display it rather than showing their site from mine - their style and my style clash terribly.
$json = file_get_contents('http://forums.zybez.net/runescape-2007-prices/api/rune+axe');
$obj = json_decode($json,true);
$blah1 = implode( $obj[0]["offers"][1]);
print_r($blah1);
If you know where it is, you should be able to just grab it and show it out?
You can use a failsafe to check if it is present with is_array() and isset() functions - see php.net docs on them.
Your print_r should give you good valid info -- try to wrap it around <pre></pre> tags before for better readability or view the source - it will be easier!
<pre><?php print_r($obj) ?></pre>
This should be your starting point, and from here you will either take the first one of your items or loop through all with
foreach ($obj as $o) { //should be $objects, not $obj
//do whatever with $o, like echo $o['price']
}
Each offers row is a table with each field separated by row:
$item = json_decode(file_get_contents('http://forums.zybez.net/runescape-2007-prices/api/rune+axe'));
while ($offer = array_shift($item[0]->offers)) {
echo "<table>" . PHP_EOL;
foreach ($offer as $field => $value) {
echo "<tr><th>$field</th><td>$value</td></tr>" . PHP_EOL;
}
echo "</table>" . PHP_EOL;
}
http://codepad.org/C3PQJHqL
Tables in HTML:
http://jsfiddle.net/G5QqZ/

I need help sorting out an if statement in a simplexml statement

Some basic background ...
I have a form that enters data to an xml file and another page that displays the data from teh xml depending that it meets the requirements . All of this I have managed to get done and thanks to a member on here I got it to show only the data as long as it has todays date and status is out . But I am left with the problem of trying to sort an if statement which needs to show data if it has it or show another div if not .
My Code ...
$lib = simplexml_load_file("sample.xml");
$today = date("m/d/y");
$query = $lib->xpath("//entry[.//date[contains(., '$today')]] | //entry[.//status[contains(., 'out')]]");
foreach($query as $node){
echo "<div id='one'>$node->name</div>
<div id='two'>$node->notes</div>
<div id='three'><div class='front'>$node->comments</div></div>";
}
So to reiterate if query returns matched data do the foreach else show another div
I only wish to know the right code for the if else statement if soneone could help with this I would be very grateful and will up vote any answer as soon as I have the reputation in place . I also apologise in advance if the question has been asked before or if it is too vague thanks again .
If xpath fails to resolve the path, it will return false (see here). Wrap the foreach loop in a simple check:
if( $query ) {
foreach($query as $node){
...
}
}
else {
// Echo the special div.
}
Since PHP is loose typed, if xpath happens to return an empty array, this check will also handle that case. Be aware that if the xpath call does return false, there may be a separate error at play that may require additional or alternative handling.

How To Stop Duplicates Being Listed On PHP Results?

I've made up a PHP script which assigns a score to listings on a website and assigns it to the results page. I have got it to work in that it shows the score and the details but it keeps listing the same results over and over.
I can't work out what it is doing but there is a small section of code I was hoping would prevent duplicate listings. Could anyone give it a tweak and see if I am going wring somewhere?
The Code is:
$dupCatch .= $adId.",";
$dupResults = explode(',', $dupCatch);
foreach($dupResults as $dupResult){
if($dupResult == $adId){
print "";
} else {
print $showResults;
$scoreBox = 'THIS IS THE SCORE: ' . $finalScore . '';
print $scoreBox;
}
}
Thanks in advance!
Jack
The problem is that you add your current $adId to the duplicate list before you check if it is there - which it will always be, of course.
Storing a bunch of numbers in a string, explodeing it every time, is a little weird, use an array instead. You also don't need to manually loop through all the items, just use in_array()
if( !in_array($adId, $dupCatch) ){
print $showResults;
$scoreBox = 'THIS IS THE SCORE: ' . $finalScore . '';
print $scoreBox;
}
$dupCatch[] = $adId;
Needless to say: it would be a better idea to fix the part that gives you the duplicate results in the first place.
You can either try to use array_unique from php side or use unique attribute at field in mysql this way duplicates can be prevent before even inserting them.

Filtering specific data from XML using PHP (Last.fm) UPDATE

Update:
Thanks Rambo for the great answer. The only issue that I have now is that it only displays artist information so long as the artists next gig is in the UK. For example, if they're playing in France and THEN the UK - it won't display anything (Or it will display my else message). If their next gig IS in the UK, then it will echo artist information etc. Any idea how to get it to echo only UK information, regardless if they're in another country before hand?
Thank you.
Original Post:
I'm currently creating a website for my final major project. I retrieve data using the Last.fm API using PHP and XML. It's going well so far, but there are a few issues I'm having trouble with. I'm very new to PHP, so I want to use this opportunity to develop some skills.
I want to limit the data to my city or country.
How do I retrieve images from an XML document?
Using the last.fm API, more specifically, the artist.getEvents (http://bit.ly/zYzWo6) - I am able to create a basic search field so that the user can type in an artist name. This is a great step in the right direction, but the problem is, any results outside of my country is irrelevant for my project. Using artist.getEvents doesn't allow any specific parameters such as location - geo.getEvents (http://bit.ly/wpSQwd) does however.
The following is the code used for my basic search:
<?php
$first_bit_of_url = 'http://ws.audioscrobbler.com/2.0/?method=artist.getevents&artist=';
$last_bit_of_url = '&api_key=b25b959554ed76058ac220b7b2e0a026&d';
$artist = ($_GET["artist"]); // gets the information passed by the input form
$query_url = $first_bit_of_url . $artist . $last_bit_of_url ;
$upcoming_gig_data_xml = simplexml_load_file($query_url);
$search_result = $upcoming_gig_data_xml->events->event->artists->artist;
$venue_result = $upcoming_gig_data_xml->events->event->venue->name;
$city_result = $upcoming_gig_data_xml->events->event->venue->location->city;
for ($i = 0; $i < 5; $i++){
echo $search_result . "<br />";
echo $venue_result . ", ";
echo $city_result . "<br />";
} ?>
Secondly how would I go about retrieving an image from, for example, this sample of XML code used in the above context? I've briefly read some articles on Xpath, can I mix the Xpath method with the method I'm using above?
<image size="small">...</image>
<image size="medium">...</image>
<image size="large">...</image>
Hopefully someone can point me in the right direction here, and I appreciate any help given.
Thanks,
Chris.
You could use XPath to get only the event elements with UK venues.
$lfm = simplexml_load_file('http://ws.audioscrobbler.com/2.0/?method=artist.getevents&artist=metallica&api_key=b25b959554ed76058ac220b7b2e0a026&d');
$uk_events = $lfm->xpath('events/event[venue/location/country="United Kingdom"]');
foreach ($uk_events as $event) {
$venue_city = (string) $event->venue->location->city;
$large_pics = array_map('strval', $event->xpath('image[#size="large"]'));
// Do whatever other processing/displaying you likeā€¦
}
(See it running.)
for your second question: use simple xml http://www.php.net/manual/de/ref.simplexml.php
for example your xml might be:
<?xml version="1.0" encoding="UTF-8"?>
<images>
<image size="small">1</image>
<image size="medium">2</image>
<image size="large">3</image>
</images>
load the xml file with simple xml and access the nodes like this. This is just a simple example.
$r = simplexml_load_file('test.xml');
foreach($r->image as $img) {
print $img . ' and size is ' . $img['size'] . "<br/>";
}
$smallimg = $upcoming_gig_data_xml->events->event->venue->image['small'];
then you can echo the image out using the img html tag, giving it's src the value of $smallimg
I haven't tested this, but hopefully it'll get you in the right direction
update
for the first point, loop through the xml file and do a match for the country so if it is equal to the united kingdom then process everything, otherwise it will skip it
foreach($upcoming_gig_data_xml->events->event as $event)
{
if($event->location == "United Kingdom")
{
// process everything here
}
}

Displaying a JSON array in PHP (from freebase)

This is a very basic question, so excuse my lack of knowledge.
I'm trying to output a JSON query from Freebase in PHP. I've already been able to parse the JSON into PHP using cURL and json_decode.
Here is a link to the JSON array (for some reason I can't get this to link directly):
http://www.freebase.com/api/service/mqlread?query={%20%22query%22%3A%20[{%20%22type%22%3A%20%22%2Fpeople%2Fperson%22%2C%20%22ns0%3Atype%22%3A%20%22%2Fbase%2Fbillionaires%2Fbillionaire%22%2C%20%22employment_history%22%3A%20[{%20%22company%22%3A%20null%20}]%2C%20%22name%22%3A%20null%20}]%20}
I'm able to ouput the first level of the array (Bill Gates), but not the 2nd level (Microsoft).
I've figured out how to display and loop through the people's names, just not their associated companies.
So my code, thus far, gets me a list of names.
$results = json_decode($response)->result;
foreach ($results as $name) {
echo $name->name . '<br/>';
I want the companies associated with each name to be displayed.
The browser-format should be:
Person 1 Name:
Company Name 1
Company Name 2
etc.
Person 2 Name:
Company Name 1
etc.
Thanks for any pointers--I'm sure that I'm just missing the simple way to structure the PHP code to display this easily.
How about:
$results = json_decode($response)->result;
foreach ($results as $person) {
echo $person->name . '<br/>';
foreach($person->employment_history as $employer) {
echo $employer->company . '<br/>';
}
echo '<hr />'; // horizontal rule for good measure
}

Categories