How to parse XML using PHP - php

I've this code
$xml = simplexml_load_file("http://api.hostip.info/?ip=12.215.42.19");
echo $xml->getName() . "<br />";
foreach($xml->children() as $child) {
echo $child->getName() . ": " . $child . "<br />";
}
If I visit http://api.hostip.info/?ip=12.215.42.19 directly on the browser, I can see the XML return but when I tried the above code, only HostipLookupResultSet<br /> gets echoed.
How do I retrieve the data from this xml? I'm interested in getting coutry and country abbreviation.
I was trying something like echo $xml->HostipLookupResultSet->gml:featureMember->Hostip->countryName but it seems it is wrong.

This might work if you query using xpath :-
// optional for register namespace into xpath
$xml->registerXPathNamespace('gml', 'http://www.opengis.net/gml');
$result = $xml->xpath('//*[self::countryName or self::countryAbbrev]');

You need to add the namespace.
See the code bellow
/* #var $xml SimpleXMLElement */
echo $xml->getName() . "\n";
$namespaces = $xml->getDocNamespaces();
foreach($xml->children($namespaces['gml']) as $child) {
echo $child->getName() . ": " . $child . "\n";
}

You can try the following code for getting Country and Country Abbrevation:
$xml = simplexml_load_file("http://api.hostip.info/?ip=12.215.42.19");
$cntry= $xml->xpath('//gml:featureMember');
foreach($cntry as $child) {
echo $child->Hostip->countryName;
echo "<br />";
echo $child->Hostip->countryAbbrev;
}

Related

Getting XML node names without duplicating in simplexml_load_file

I'm getting the node names of an XML using this code:
$url = 'https://www.toptanperpa.com/xml.php?c=shopphp&xmlc=e7ef2a0122';
$xml = simplexml_load_file($url) or die("URL Read Error");
echo $xml->getName() . "<br>";
foreach ($xml->children() as $child) {
echo $child->getName() . "<br>";
foreach ($child->children() as $child2) {
echo $child2->getName() . "<br>";
foreach ($child2->children() as $child3) {
echo $child3->getName() . "<br>";
foreach ($child3->children() as $child4) {
echo $child4->getName() . "<br>";
}
}
}
}
I'm getting the nodes and children correctly, however, it's duplicating.
Result is as below:
urunler
urun
urun_aktif
urun_metaKeywords
urun_metaDescription
urun_url
urun
urun_aktif
urun_metaKeywords
urun_metaDescription
urun_url
Should I just use array_unique or is there a better method?
Thanks
i used recursive function this is simple
function getChildrens($x) {
$children = array();
array_push($children, $x->getName());
foreach ($x->children() as $chld) {
$children = array_merge($children, getChildrens($chld));
}
return array_unique($children);
}
echo implode("<br>", getChildrens($xml));

How to make foreach work with this PHP script - GET API

I'm working on a script that will retrieve API information of the 'near earth objects' from NASA's website. User selects date, api grabs the information and displays it. How do I fix the foreach in this script? would appreciate some help with this.
$jsonAsteroids = file_get_contents("https://api.nasa.gov/neo/rest/v1/feed?start_date=2018-08-01&end_date=2018-08-04&api_key=NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo");
$data = json_decode($jsonAsteroids, true);
echo "<h4>Retrieving the first element (i.e. \"links\") of the JSON structure</h4>";
var_dump( $data["links"]);
echo "<h4>Retrieving the first element (i.e. \"next\") inside the \"links\" element</h4>";
echo( $data["links"]["next"]);
You were very close. Your main issue was that you used json_decode(..., true); which gives you an array, but then used the object->property syntax instead of object['property']. My suggestion is to use json_decode without the 2nd argument in this case.
Finally, your 2nd foreach was malformed.
<?php
$result = file_get_contents("https://api.nasa.gov/neo/rest/v1/feed?start_date=2018-08-01&end_date=2018-08-04&api_key=NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo");
$data = json_decode($result);
foreach ($data->near_earth_objects as $date => $objects) {
echo "<p>" . count($objects) . " objects detected on $date</p>";
echo "<ol>";
foreach ($objects as $object) {
echo "<li>" . $object->name . " <a href='" . $object->nasa_jpl_url . "'>" . $object->nasa_jpl_url . "</a><br>";
echo "Diameter of the object: " . $object->estimated_diameter->meters->estimated_diameter_min . "-" . $object->estimated_diameter->meters->estimated_diameter_max . " metres<br>";
echo "<ul>";
foreach ($object->close_approach_data as $close_approach) {
echo "<li>Close approach: " . $close_approach->close_approach_date . " traveling at a velocity of " . $close_approach->relative_velocity->kilometers_per_hour . " km/h " . "missing " . $close_approach->orbiting_body . " by " . $close_approach->miss_distance->kilometers . " km</li> ";
}
echo "</ul>";
}
echo "</ol>";
}

PHP (XML TO ARRAY) Getting the attribute of the xml that is array

Hello I am getting games in the spilgames xml. I managed to convert it to array but 1 problem came up again the problem is that the string I want to get is inside of an array or an attribute of 1 node xml .I can't get the attribute.
I want to get the attribute.
website of spilgames: here
Code I have so far:
<?php
$xml = simplexml_load_string(file_get_contents('http://publishers.spilgames.com/rss-3?limit=100&format=xml&category=Action')); /* Get the xml */
$json = json_encode($xml);
$games = json_decode($json); /* Make it an array */
$game = $games->entries->entry;
foreach($game as $entry) { /* Each game information */
echo $entry->title;
echo $entry->id;
echo $entry->description;
echo $entry->category;
echo $entry->subcategory;
echo $entry->technology;
echo $entry->player->url;;
echo $entry->thumbnails->small->url; /* Problems starts here */
/* Because the thumbnails has 3 child but the info is inside of each child */
}
?>
I am getting the xml not json in spilgames because I don't know how json works.
If I were you I would learn how JSON works because it will make your life easier:
<?php
$json = file_get_contents('http://publishers.spilgames.com/rss-3?limit=100&format=json&category=Action');
$data = json_decode($json);
foreach ($data->entries as $entry) {
echo $entry->title . "\n";
echo $entry->id . "\n";
echo $entry->description . "\n";
echo $entry->category . "\n";
echo $entry->subcategory . "\n";
echo $entry->technology . "\n";
echo $entry->thumbnails->small . "\n";
echo $entry->thumbnails->medium . "\n";
echo $entry->thumbnails->large . "\n";
}
?>

simplexml 'Trying to get property of non-object in' error

I'm trying to parse the XML of http://www.mpgh.net/forum/external.php?type=RSS2&forumids=175
but I get this error, can't find whats wrong.
Notice: Trying to get property of non-object in C:\xampp\htdocs\crossfire\index.php on line 9
<?php
$rss = simplexml_load_file('http://www.mpgh.net/forum/external.php?type=RSS2&forumids=175');
for($i=0;$i<10;$i+=1) {
$namespaces = $rss->getNameSpaces(true);
$dc = $rss->children($namespaces['dc']);
echo "Title: " . $rss->channel->item[$i]->title . "<br>";
echo "Creator: " . $dc->channel->item[$i]->creator . "<br>";
echo "Link: " . $rss->channel->item[$i]->link . "<br><br>";
}
And my second question.
Why is this code only working properly at http://www.mpgh.net/forum/external.php?type=RSS2&forumids=175 and not at other pages like http://www.mpgh.net/forum/external.php?type=RSS2&forumids=168
Notice: Trying to get property of non-object in C:\xampp\htdocs\crossfire\index.php on line 7
<?php
$rss = New DOMDocument();
$rss = simplexml_load_file('http://www.mpgh.net/forum/external.php?type=RSS2&forumids=168');
for($i=0;$i<10;$i+=1) {
if (substr($rss->channel->item[$i]->title, 0, 9) == '[Release]') {
echo "Title: " . $rss->channel->item[$i]->title . "<br>";
echo "Link: " . $rss->channel->item[$i]->link . "<br><br>";
} else {
echo 'Hoi<br><br>';
}
}
Thanks.
I think the problem is that $ith index of $rss->channel->item is not set or not an object.
Try this; it will expose the problem:
$rss = simplexml_load_file('http://www.mpgh.net/forum/external.php?type=RSS2&forumids=175');
if ($rss===null || !is_object($rss))
die('Failed to load xml file.');
if (!is_object($rss->channel))
die('Channel is not an object!');
foreach ($rss->channel->item as $item)
if (is_object($item)) {
$namespaces = $rss->getNameSpaces(true);
$dc = $rss->children($namespaces['dc']);
echo "Title: " . $item->title . "<br>";
echo "Creator: " . $item->creator . "<br>";
echo "Link: " . $item->link . "<br><br>";
}

parsing a xml to get some values

http://www.managerleague.com/export_data.pl?data=transfers&output=xml&hide_header=0
These are player sales from a browser game. I want to save some fields from these sales. I am fetching that xml with curl and storing on my server. Then do the following:
$xml_str = file_get_contents('salespage.xml');
$xml = new SimpleXMLElement($xml_str);
$items = $xml->xpath('*/transfer');
print_r($items);
foreach($items as $item) {
echo $item['buyerTeamname'], ': ', $item['sellerTeamname'], "\n";
}
The array is empty and i cant seem to get anything from it. What am i doing wrong?
There is no reason to use cURL or XPath for that. You can do
$url = 'http://www.managerleague.com/export_data.pl?data=transfers&output=xml&hide_header=0';
$transfers = new SimpleXMLElement($url, NULL, TRUE);
foreach($transfers->transfer as $transfer) {
printf(
"%s transfered from %s to %s\n",
$transfer->playerName,
$transfer->sellerTeamname,
$transfer->buyerTeamname
);
}
Live Demo
You forgot a slash in your xpath:
$xml_str = file_get_contents('salespage.xml');
$xml = new SimpleXMLElement($xml_str);
$items = $xml->xpath('/*/transfer');
print_r($items);
foreach($items as $item) {
echo $item->buyerTeamname, ': ', $item->sellerTeamname, "\n";
}
<?php
$xml = simplexml_load_file("test.xml");
echo $xml->getName() . "<br />";
foreach($xml->children() as $child)
{
echo $child->getName() . ": " . $child . "<br />";
}
?>
Is this what you want?

Categories