Good, again I ask your help, I have a xml file (http://radiojoven.6te.net/AirPlayHistory.xml) with several songs and I just wanted to take the song "I Need Your Love" from "SHAGGY "but I using a code I found here can not, appears all the songs. Could help me solve the problem?
<?php
$xml = simplexml_load_file("http://radiojoven.6te.net/AirPlayHistory.xml");
foreach($xml->Song as $item)
echo $item->Artist['name'] . " - " . $item['title'] ."<br>";
?>
Thanks!
I think what you are looking for a conditional control structures, namely if (I'm sorry if I'm something you already know). So inside your loop you can go:
foreach($xml->Song as $item) {
if ($item->Artist['name'] == 'SHAGGY' && $item['title'] == 'I NEED YOUR LOVE') {
echo $item->Artist['name'] . " - " . $item['title'] ."<br>";
}
}
(Sorry for the unrealistic example, you probably get the derails for the conditionals in variables).
There are other ways to query and filter things specific to XML documents, namely xpath that use can use as well.
Related
I'm new to PHP and in particularly XML.
I'm trying to pull data from an XML file using the particular values of one of the child nodes. All the online resources I seem to find lead me to how to get all the values from a child node but I want to pull only the ones that contain a certain value in a child node. I'm struggling to get the format of the if statement right.
Any help, much appreciated, thank you!
My code so far:
if( !($xml = simplexml_load_file('images/database.xml')) )
{
echo "Unable to load XML file";
}
else
{
foreach($xml->children() as $document)
{
if ($xml->$document->city == $xml->$document->city['London'])
{
echo $document->name . ", ";
echo $document->description . ", ";
echo $document->image . ", <br>";
}
}
}
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);
}
}
I have a problem that's born of being a dyed in the wool procedural programmer who's here forced into using some OOP constructs in order to make use of a library I need to use. I am stuck unable to access variables- other than print them out. Let me illustrate:
foreach($html->find('span[class="given-name"]') as $e)
echo $e->innertext . '<br>';
foreach($html->find('span[class="family-name"]') as $e)
echo $e->innertext . '<br>';
The above will print out a long list of first names, followed by a long list of surnames. However I want to be able to access them together. For example I want to be able to say something like $myarray["firstname"] = (*whatever is in $e->innertext*) and also $myarray["surnamename"] = (*whatever is in the next $e->innertext*)
When I try the seemingly obvious:
$x = $e->innertext;
it crashes. I assume that's because I am passing a pointer to $x instead of a value, but how on earth do I tell it I want the value - in this case a part of a person's name, to be assigned to $x, or my array, or whatever the variable might be?
I am almost a complete neophyte when it comes to OOP concepts and constructs, so please bear that in mind. Thank you for your assistance!
If your document is well structured and in order, this should do the trick:
$name=array();
$surname=array();
foreach($html->find('span[class="given-name"]') as $e){
$name[]=$e->innertext;
}
foreach($html->find('span[class="family-name"]') as $e){
$surname[]=$e->innertext;
}
foreach($name as $key=>$value){
echo $name[$key] . " " . $surname[$key] . "<br>";
}
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
}
}
I've been scouring around for information through the google Calendar API, the Zend docs, and here, and just about everything I find seems to make assumptions on what I already know about PHP, so I'm just getting more lost. I do have a good deal of programming experience... with... um... a FORTH variant. Anyway! I'm trying to pass the output of a PHP script that can be used to get all of the important data from a calendar event into said FORTH variant. What's driving me up the wall is that I can't figure out how to grab something as simple as the UID of a message. Here's what I'm working with:
function outputCalendar($client)
{
$gdataCal = new Zend_Gdata_Calendar($client);
$eventFeed = $gdataCal->getCalendarEventFeed();
foreach ($eventFeed as $event) {
echo $event->title->text . " (" . $event->id->text . ")\n";
foreach ($event->when as $when) {
echo $when->startTime . "\n";
}
}
}
This is based off the example code they gave me, and instead of formatting with with XML tags like in the example, just puts each on its own new line (which is easier for me to pull into the other language.)
Now, I tried to add echo $when->startTime . "\n"; to the loop, but it just tells me:
Fatal error: Uncaught exception 'Zend_Gdata_App_InvalidArgumentException' with message 'Property uid does not exist' in /var/mucktools/Zend/Gdata/App/Base.php:484
So, obviously, I'm going about grabbing the UID the wrong way. Now, here's the thing. These two lines:
echo $event->title->text . " (" . $event->id->text . ")\n";
echo $when->startTime . "\n";
...are pulling data from the event. However, 'title'. 'text', 'startTime' all look like things pulled out of one's posterior. I know, cognitively, that can't be true. There is a library and an API here. But I want to know where I can find a listing of all the crap I can pull out of $event and what the syntax is to do so. Can anyone help me with this?
And before you ask, yes, I have a very good reason to be grabbing the output of a PHP script and stuffing it into an obscure FORTH variant. And no, there's not another way that won't be more complicated than this one. I've done my homework here.
I'm sure you've read the documentation for Zend Gdata. It tells you that you need to provide getCalendarEventFeed() with a Zend_Gdata_Query object, otherwise I think you just get public data back.
Your code then should look something like this:-
$service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
$user = "user#gmail.com";
$pass = "userpassword";
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
$gDataCal = new Zend_Gdata_Calendar($client);
$query = $gDataCal->newEventQuery();
$query->setVisibility('private');
$query->setProjection('full');
$query->setOrderby('starttime');
$query->setFutureevents('true');
$eventFeed = $gDataCal->getCalendarEventFeed($query);
foreach ($eventFeed as $event) {
echo $event->title . " (" . $event->id . ")\n";
foreach($event->when as $when){
echo $when->startTime . "\n";
}
}
Hopefully that should get you started in the right direction.
Also the php_openSSL module has to be enabled in PHP for this to work, but I assume you have that already enabled to get as far as you did.