parsing a xml to get some values - php

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?

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));

Read xml response using php

I have a Api response in XML format.How can I get gps_x and gps_y for both elements.
$url="http://www.tixik.com/api/nearby?lat=36.106121163930377&lng=28.07762145996093&limit=2&key=demo";
$xmlinfo = simplexml_load_file($url);
print_r($xmlinfo);
echo $xmlinfo['gps_x']; // outputs nothing
echo $xmlinfo -> gps_x; // outputs nothing
How can I get gps_x and gps_y from above response?
I did this by getting the content from url then converting to json using exceptions handling and get the data from decoded json:
<?php
$myXMLData = file_get_contents("http://www.tixik.com/api/nearby?lat=36.106121163930377&lng=28.07762145996093&limit=2&key=demo");
$simpleXml = simplexml_load_string($myXMLData) or die("Error: Cannot create encode data to xml object");
$jsondata = json_encode($simpleXml) or die("Error: Cannot encode record to json");
$data = json_decode($jsondata, true);
$in = $data['items']['item'];
foreach ($in as $key => $value) {
echo "ID= " . $in[$key]['id'] . ", GPS-x = " . $in[$key]['gps_x'] . ", GPS-y = " . $in[$key]['gps_x'];
echo "<br/>";
}
?>
OUTPUT
ID= 2354292, GPS-x = 36.1065000000, GPS-y = 36.1065000000
ID= 2431066, GPS-x = 36.0949905151, GPS-y = 36.0949905151
If you want to take the data from XML directly:
<?php
$myXMLData = file_get_contents("http://www.tixik.com/api/nearby?lat=36.106121163930377&lng=28.07762145996093&limit=2&key=demo");
$simpleXml = simplexml_load_string($myXMLData) or die("Error: Cannot create encode data to xml object");
$in = $simpleXml->items->item;
foreach ($in as $key) {
echo "ID= " . $key->id;
echo ", GPS-x = " . $key->gps_x;
echo ", GPS-y = " . $key->gps_y . "<br/>";
}
?>
OUTPUT
ID= 2354292, GPS-x = 36.1065000000, GPS-y = 28.0684000000
ID= 2431066, GPS-x = 36.0949905151, GPS-y = 28.0860328674
Looking at the print_r() output, it show that the gps_x & gps_y are part of an item and not directly under the xmlinfo object.
Here is the code that will do the job:
$url = "http://www.tixik.com/api/nearby?lat=36.106121163930377&lng=28.07762145996093&limit=2&key=demo";
$xmlinfo = simplexml_load_file($url);
if ($xmlinfo->items && $xmlinfo->items->item) {
$item = $xmlinfo->items->item;
print $item->gps_x . "\n";
print $item->gps_y . "\n";
}
$url="http://www.tixik.com/api/nearby?lat=36.106121163930377&lng=28.07762145996093&limit=2&key=demo";
$xmlinfo = simplexml_load_file($url);
foreach ($xmlinfo->items->item as $item) {
//echo "<pre>";print_r($item);
echo "<br />". $item->gps_x;
echo "<br />". $item->gps_y;
}

Buffering or moving PHP data to display in a different part of a webpage

I am parsing a very large XML file with XMLReader.
$reader = new XMLReader;
$reader->open('products.xml');
$dom = new DOMDocument;
$xpath = new DOMXpath($dom);
while ($reader->read() && $reader->name !== 'product') {
continue;
}
A while loop is used to display relevant data based on user input as well as building arrays with XML values.
while ($reader->name === 'product') {
$node = $dom->importNode($reader->expand(), TRUE);
if ($xpath->evaluate('number(price)', $node) > $price_submitted) {
$category = $xpath->evaluate('string(#category)', $node);
$name = $xpath->evaluate('string(name)', $node);
$price = $xpath->evaluate('number(price)', $node);
// Relevant search results displayed here:
echo "Category: " . $category . ". ";
echo "Name: " . $name . ". ";
echo "Price: " . $price . ". ";
$nameArray[] = $name;
}
$reader->next('product');
}
The foreach loop below uses the array that is built in the while loop above. I need these values (displayed in this foreach loop below) to appear BEFORE the while loop above displays the relevant search results. With XMLReader, you can only execute one while loop for each time you parse the XML, and I don't want to parse it twice because of memory and overhead issues. What is the best way to do this?
foreach ($nameArray as $names) {
echo $names . " ";
}
Well… there are not many options. The most effectiv straight-forward approach is to store category/name/price in array instead of outputting them directly:
<?php
$data = array();
while ($reader->name === 'product') {
$node = $dom->importNode($reader->expand(), TRUE);
if ($xpath->evaluate('number(price)', $node) > $price_submitted) {
$category = $xpath->evaluate('string(#category)', $node);
$name = $xpath->evaluate('string(name)', $node);
$price = $xpath->evaluate('number(price)', $node);
$data[] = array($category, $name, $price);
$nameArray[] = $name;
}
$reader->next('product');
}
foreach ($nameArray as $names) {
echo $names . " ";
}
foreach ($data as $datum) {
// Relevant search results displayed here:
echo "Category: " . $datum[0] . ". ";
echo "Name: " . $datum[1] . ". ";
echo "Price: " . $datum[2] . ". ";
}
In case that doesn't work memory-wise (you mentioned that XML file is really large) you should use db- or file-backed temporary storage

Trying to read values from an XML feed and display them in PHP

I'm trying to display values from this xml feed:
http://www.scorespro.com/rss/live-soccer.xml
In my PHP code I have the following loop but it does not display the results on my page:
<?php
$xml = simplexml_load_file("http://www.scorespro.com/rss/live-soccer.xml");
echo $xml->getName() . "<br>";
foreach($xml->children() as $item)
{
echo $item->getName() . ": " . $item->name . "<br>";
}
?>
For some reason it only shows:
rss
channel:
I'm fairly new to how XML works so any help would be much appreciated.
You can get actual data from $xml->channel->item so use like below
$items = $xml->channel->item;
foreach($items as $item) {
$title = $item->title;
$link = $item->link;
$pubDate = $item->pubDate;
$description = $item->description;
}
DEMO.
you can use below code
$dom = new DOMDocument;
$dom->loadXML($url);
if (!$dom) {
echo 'Error while parsing the document';
exit;
}
$xml = simplexml_import_dom($dom);
$data = $xml->channel->item;

How to parse XML using 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;
}

Categories