I'm really stuck and would appreciate any advice. I have an XML document I want to be able to read but I can't get it to work with either Jquery or PHP. I have read multiple pages on online and tried everything including JSON encoding. I have read nearly a hundred tutorials online but everything I do doesn't seem to work. Is anybody able to write a script that can enable me to use some of the nodes in my document? The code below is the best I have been able to do so far. Is anybody able to make it so I can loop through the nodes etc?
To the person who marked this as a duplicate I have tried to look at those questions but I can't access the URL. I therefore can't compare the nodes/etc to see what I am doing wrong. I would really appreciate some help as I am quite new to this.
Thanks in advance for your help
<?php
$url = "https://developerdemo.isams.cloud/api/batch/1.0/xml.ashx?
apiKey=0A1C996B-8E74-4388-A3C4-8DA1E40ADA57";
$xml = simplexml_load_file($url);
$myJSON = json_encode($xml);
?>
<script>
var name='<?php echo $myJSON; ?>';
$.each(name, function(key, value) {
alert( "The key is '" + key + "' and the value is '" + value + "'" );
});
</script>
Once you have the code you already have it's simply a case of working with the XML structure, the following example loads the XML and then gives a list of the pupils (with a few details)...
$url = "https://developerdemo.isams.cloud/api/batch/1.0/xml.ashx?apiKey=0A1C996B-8E74-4388-A3C4-8DA1E40ADA57";
$xml = simplexml_load_file($url);
foreach ( $xml->PupilManager->CurrentPupils->Pupil as $pupil) {
echo $pupil['Id']." ".$pupil->SchoolCode." ".$pupil->Surname.PHP_EOL;
}
The id it puts out is the Id attribute of the Pupil element, the SchoolCode is the SchoolCode element in the Pupil.
The first few lines of output are...
1 101314800 Richards
3 PRE0000003SUF Thomas
5 PRE0000005SUF Davies
7 PRE0000007SUF Poole
What you can do is:
header('Content-Type: text/plain');
$resultArray = file_get_contents('path/to/file.xml');
$resultArray = (array)simplexml_load_string($resultArray);
The result will be an array of XML Objects and arrays, which you can access later via their property name or index respectively ($resultArray["foo"]->foo).
Related
I have some php code that extracts a web address. The object I have extracted is of the form:
WEBSITE?flage=2&fgast=48&frat=1&sort=D&fsrc=2&wid=bf&page=1&id=16123012&source=searchresults
Now in PHP I have called this object $linkHREF
I want to extract the id element only and put it into an array (I'm bootstrapping this process to get multiple id's)
So the command is:
$detailPagePathArray = explode("id=",$linkHREF); #Array
Now the problem is the output of this includes what comes after the id tag, so the output looks like:
echo $detailPagePathArray[0] = WEBSITE?flage=2&fgast=48&frat=1&sort=D&fsrc=2&w
echo $detailPagePathArray[1] = bf&page=1&
echo $detailPagePathArray[2] = 16123012&source=searchresults
Now the problem is obvious, where it'd firstly picking up the "id" in the "wid" marker and cutting it there, however the secondary problem is it's also picking up all the material after the actual "id". I'm just interested in picking up "16123012".
Can you please explain how I can modify my explode command to point it to the particular marker I'm interested in?
Thanks.
Use the built-in functions provided for the purpose.
For example:
<?php
$url = 'http://www.example.com?flage=2&fgast=48&frat=1&sort=D&fsrc=2&wid=bf&page=1&id=16123012&source=searchresults';
$qs = parse_url($url);
parse_str($qs['query'], $vars);
$id = $vars['id'];
echo $id; // 16123012
?>
References:
parse_url()
parse_str()
if you are sure that you are getting &id=123456 only once in your object, then below
$linkHREF = "WEBSITE?flage=2&fgast=48&frat=1&sort=D&fsrc=2&wid=bf&page=1&id=16123012&source=searchresults";
$str = current(explode('&',end(explode('&id', $linkHREF,2))));
echo "id" .$str; //output id = 16123012
Hi I have never used xml but need to now, so I am trying to quickly learn but struggling with the structure I think. This is just to display the weather at the top of someones website.
I want to display Melbourne weather using this xml link ftp://ftp2.bom.gov.au/anon/gen/fwo/IDV10753.xml
Basically I am trying get Melbourne forecast for 3 days (what ever just something that works) there is a forecast-period array [0] to [6]
I used this print_r to view the structure:
$url = "linkhere";
$xml = simplexml_load_file($url);
echo "<pre>";
print_r($xml);
and tried this just to get something:
$url = "linkhere";
$xml = simplexml_load_file($url);
$data = (string) $xml->forecast->area[52]->description;
echo $data;
Which gave me nothing (expected 'Melbourne'), obviously I need to learn and I am but if someone could help that would be great.
Because description is an attribute of <area>, you need to use
$data = (string) $xml->forecast->area[52]['description'];
I also wouldn't rely on Melbourne being the 52nd area node (though this is really up to the data maintainers). I'd go by its aac attribute as this appears to be unique, eg
$search = $xml->xpath('forecast/area[#aac="VIC_PT042"]');
if (count($search)) {
$melbourne = $search[0];
echo $melbourne['description'];
}
This is a working example for you:
<?php
$forecastdata = simplexml_load_file('ftp://ftp2.bom.gov.au/anon/gen/fwo/IDV10753.xml','SimpleXMLElement',LIBXML_NOCDATA);
foreach($forecastdata->forecast->area as $singleregion) {
$area = $singleregion['description'];
$weather = $singleregion->{'forecast-period'}->text;
echo $area.': '.$weather.'<hr />';
}
?>
You can edit the aforementioned example to extract the tags and attributes you want.
Always remember that a good practice to understand the structure of your XML object is printing out its content using, for instance, print_r
In the specific case of the XML you proposed, cities are specified through attributes (description). For this reason you have to read also those attributes using ['attribute name'] (see here for more information).
Notice also that the tag {'forecast-period'} is wrapped in curly brackets cause it contains a hyphen, and otherwise it wouldn generate an error.
I know this may sound similar to some past Q/As, I think mine is slightly different though.. I have a webpage which I want to dynamically load text file information. I upload the text file through an iframe and I want to save this information from php to Javascript. Whenever I try to save this as a regular variable it doesn't work so I have tried to do this by saving this information as a part of the $_POST array under a hidden form named $_POST['hidden_form']. Whenever I try to read the php into Javascript, I keep getting an error "Unexpected token ILLEGAL." I have tried the following two codes:
for($i=0;$i< count($_POST['hidden_form']) ;$i++)
{
echo "saved_form[$i]='" . $_POST['hidden_form'][$i]. "';\n";
}
and
saved_form = <?php echo json_encode($_POST['hidden_form']); ?>;
Assigning a php array into a javascript array
I think the error has to do with the " ' " needed to specify the array but not sure. I have no idea where to go from here so any help would be GREATLY appreciated. If there are better methods to do this please let me know. Thanks in advance!
saved_form = '<?php echo addslashes(json_encode($_POST['hidden_form'])); ?>';
Or
for($i=0;$i< count($_POST['hidden_form']) ;$i++)
{
echo "saved_form[$i]='" . addslashes($_POST['hidden_form'][$i]) . "';\n";
}
Both should work, probably had quotes breaking something?
the best way i have used is,
text/javascript
var saved_form = <?php echo json_encode($_POST['hidden_form']) ?>
Please note there are no Quotes around the php so your saved_form is an Object not a string json string witch would require you to to use var form_object = eval(saved_form)
#Lee might have meant this?
Just a note though i would not use the Raw $_POST pass it to a function that can loop though and addSlashes every value inside the post some thing like
<?php
function arr_addSlashes($array){
$ret = array();
foreach($array as $k => $v){
$ret[$k] = addSlashes($v);
}
return $ret;
}
?>
I'm trying to get a product list for a client from a webservices xml file over to an SQL databse using a little php script, but I can't seem to get it to work.
The relevant code is as follows:
$c = 0;
...
$xml = simplexml_load_file($completeurl);
$listingsArray = $xml->listings->listing;
foreach($listingsArray as $listing){
$addition[0] = $listing[$c]->type;
$addition[1] = $listing[$c]->condition;
//etcetera
c = c + 1;
}
The XML file is formated like:
<inventory>
<listings>
<listing>
//tags for type, condition, etc
</listing>
</listings>
</inventory>
$completeurl is a string that contains the url of the xml file
$addition is an array that's defined earlier in the code
I've been working on this for a while now, but I can't seem to figure out where the error is in my code. The problem that I'm having is that $listingsArray should have close to 100 elements in it, but is constantly coming up with 0. Anybody see what I'm doing wrong?
EDIT: I tried changing
$listingsArray = $xml->listings->listing;
to
$listingsArray = $xml->listings;
But empty strings are still being written to the $addition array. A var_dump of listingsArray show that all of the information is in there, though.
If you want each listing i believe you are going a child too deep.
$listingsArray = $xml->listings->listing;
shoudl be
$listingsArray = $xml->listings;
foreach($listingsArray as $listing){
$addition[0] = $listing[$c]->type;
$addition[1] = $listing[$c]->condition;
//etcetera
}
additionally what is $c? It also helps to post your exact errors. When debugging inserting var_dumps is extremely helpful. If you think the probelm is $listingArray
print it out and see if it contains the data you want.
changing
$listingsArray = $xml->listings->listing;
to
$listingsArray = $xml->listings;
Should solve the issue. You set $listingsArray to the array of listings, then the foreach tries to go down another level
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
}
}