How to receive XML data produced by a website(webservice) in PHP? - php

Input is a URL like this http://ws.geonames.org/children?geonameId=6255148 and I would like to receive the XML file in a SimpleXMLElement for example?

Try this as your base point:
<?php
$xml = simplexml_load_file("http://ws.geonames.org/children?geonameId=6255148");
//print_r($xml);
foreach($xml->geoname as $geo)
{
echo $geo->toponymName . "<br />";
}
?>

Related

PHP simplexml_load_file 2 tags in xml file

I have an xml file like this
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<Job>
<JobInfo>
<User>abc</User>
<Computer>acb</Computer>
<Started>2018/04/21-21:58:30:0182-06</Started>
<Ended>2018/04/21-23:10:10:0093-06</Ended>
</JobInfo>
<JobFlags>
<Active>Yes</Active>
<Complete>Yes</Complete>
</JobFlags>
</Job>
I use simplexml_load_file to load file and print out User, Computer and Complete attribute.
$xml=simplexml_load_file("abc.xml") or die("Error: Cannot create object");
foreach($xml->children() as $xm) {
echo $xm->User . "<br>";
echo $xm->Computer . "<br>";
echo $xm->Complete . "<br>";
But it only print out User and Computer. The result for Complete is empty.
Please help me with this, thank you!
The main issue is that you are trying to mix the fields from different elements. You can see from the original XML that <User> and <Computer> are in the <JobInfo> element and <Complete> is in the <JobFlags> element. This isn't a problem, but when you use your foreach loop, you go through each child element of <Job> and output all of the values for each element. If you change your loop to...
foreach($xml->children() as $tag => $xm) {
echo "element=".$tag . "<br>";
echo $xm->User . "<br>";
echo $xm->Computer . "<br>";
echo $xm->Complete . "<br>";
}
You get (please excuse wrong markup, I wanted the layout)...
element=JobInfoabcacbelement=JobFlagsYes
If instead you just need those three pieces of information from the document, you could access them using the full path and so just pick out the details your after without using a foreach...
echo $xml->JobInfo->User . "<br>";
echo $xml->JobInfo->Computer . "<br>";
echo $xml->JobFlags->Complete . "<br>";
Gives you.
abcacbYes
simplexml is a bit outdated. Not sure that a <complete> tag is valid, xml, it may be the issue.
If you can, try to use php-dom instead.
https://php.net/manual/en/book.dom.php
Example to retrieve all the tags texts.
#!/usr/bin/php
<?php
$remote =<<<'EOF'
<JobInfo>
<User>abc</User>
<Computer>acb</Computer>
<Started>2018/04/21-21:58:30:0182-06</Started>
<Ended>2018/04/21-23:10:10:0093-06</Ended>
</JobInfo>
<JobFlags>
<Active>Yes</Active>
<Complete>Yes</Complete>
</JobFlags>
EOF;
$i = 0;
$doc = new DOMDocument();
$doc->loadHTML($remote);
foreach($doc->getElementsByTagName('*') as $elem) {
echo $i++.": ".$elem->textContent;
}
The package bellong to php-xml:
Package php-dom is a virtual package provided by: php7.2-xml
Alternatives: https://php.net/manual/en/refs.xml.php
Try to wrap all elements into a parent tag:
<?xml version="1.0"?>
<test>
<JobInfo>
<User>abc</User>
<Computer>acb</Computer>
<Started>2018/04/21-21:58:30:0182-06</Started>
<Ended>2018/04/21-23:10:10:0093-06</Ended>
</JobInfo>
<JobFlags>
<Active>Yes</Active>
<Complete>Yes</Complete>
</JobFlags>
</test>
and then reference in your php:
<?php
$xml=simplexml_load_file("abc.xml") or die("Error: Cannot create object");
echo $xml->JobInfo->User . "<br>";
echo $xml->JobInfo->Computer . "<br>";
echo $xml->JobFlags->Complete . "<br>";
?>
It worked here.
I think it's just a matter of making a correct reference to the entire hierarchical structure of the tags.
See this example taken from http://php.net/manual/en/function.simplexml-load-file.php:
<?php
$xml = '<?xml version="1.0" encoding="UTF-8" ?>
<rss>
<channel>
<item>
<title><![CDATA[Tom & Jerry]]></title>
</item>
</channel>
</rss>';
$xml = simplexml_load_string($xml);
// echo does the casting for you
echo $xml->channel->item->title;
// but vardump (or print_r) not!
var_dump($xml->channel->item->title);
// so cast the SimpleXML Element to 'string' solve this issue
var_dump((string) $xml->channel->item->title);
?>
Above will output:
Tom & Jerry
object(SimpleXMLElement)#4 (0) {}
string(11) "Tom & Jerry"
Reference:
https://stackoverflow.com/a/16972780/5074998
http://php.net/manual/en/function.simplexml-load-file.php
It works just fine for me:
abc
acb
Yes
You might be confused because you are expecting it all on three consecutive lines. Try outputting it like this instead and it may help you visualize that it is echoing all three of your requested elements (whether they exist or not) for two loops (since the XML has two children):
foreach($xml->children() as $xm) {
echo "Current Element: " . $xm->getName() . "<br />";
echo "User: " . $xm->User . "<br />";
echo "Computer: " . $xm->Computer . "<br />";
echo "Complete: " . $xm->Complete . "<br />";
}
which will output:
Current Element: JobInfo
User: abc
Computer: acb
Complete:
Current Element: JobFlags
User:
Computer:
Complete: Yes
As Nick suggested in his comment, if you don't want the <br /> breaks to print when the element doesn't exist, you can use isset like:
foreach($xml->children() as $xm) {
echo isset($xm->User) ? "{$xm->User}<br />" : '';
echo isset($xm->Computer) ? "{$xm->Computer}<br />" : '';
echo isset($xm->Complete) ? "{$xm->Complete}<br />" : '';
}
Or, as NigelRen recommended in their answer, you could skip using children() if you know the full path to the elements you need, and just use those paths instead, like:
echo $xml->JobInfo->User . "<br />";
echo $xml->JobInfo->Computer . "<br />";
echo $xml->JobFlags->Complete . "<br />";
The underlying issue being that when you were echoing out $xm->Complete while traversing the JobInfo element, it was outputting just the <br /> because $xml->JobInfo->Complete does't exist.

Load XML File in PHP and add Child if not exists

i want to load XML data into my php file with address data.
Each address should also have coordinates - if not they should be added. So i am doing the following:
$xmlDatei = "AddressData.xml";
$xml = simplexml_load_file($xmlDatei);
for($i=0,$size=count($xml);$i<$size;$i++){
if($xml->RECORD[$i]->ADDRESS->LAT != NULL){
//get lat and lng stuff here...
$lat = .......
$lng = .......
echo "lat: " . $lat; // Test echo WORKING
echo "lng: " . $lng;
// Now i want to add the data to the xml
$xml->RECORD[$i]->ADDRESS->addAttribute('LAT', $lat);
$xml->RECORD[$i]->ADDRESS->addAttribute('LNG', $lng);
$xml->saveXML();
}
// Test echo NOT WORKING
echo $xml->RECORD[$i]->ADDRESS->LAT;
echo $xml->RECORD[$i]->ADDRESS->LNG;
}
So it seems like the addAttribute is not working properly here.
What am I doing wrong???
Your echo is looking for a child element called LAT:
echo $xml->RECORD[$i]->ADDRESS->LAT;
But you have added an attribute, so you need to use different syntax:
echo $xml->RECORD[$i]->ADDRESS['LAT'];
You are adding attributes to the ADDRESS tag, not nodes.
Try this:
echo $xml->RECORD[$i]->ADDRESS['LAT'];
echo $xml->RECORD[$i]->ADDRESS['LNG'];

XML PHP MYSQL data parsing

I am having a question to ask...
I am having a mysql database...
I want to make an XML file for my mysql database using PHP
I did it using newXMLELEMENT function..
Now next thing i want to do is parse my XML file data to HTML Tables & Forms..
Hoe can i add XML data to html textbox and other controls..?
<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("userimages.xml");
$x = $xmlDoc->documentElement;
foreach ($x->childNodes AS $item)
{
print $item->nodeName . " = " . $item->nodeValue . "<br>";
}
?>
this is my code..i wan tot add the fetched data to forms....but its getting print simply as i am using print function
this is my XML
i want to parse all this data in my forms ex. , etc to disabled textbox,
<ALLIMAGES>
<gal>
<imageid>6</imageid>
<imagetype>Vector</imagetype>
<image>..images/accept.png</image>
<companyname>w845</companyname>
<description>villain</description>
<status>sold</status>
<dou>2014-03-16</dou>
<like>22</like>
<price>212</price>
<color>BLUE</color>
</gal>
<gal>
<imageid>7</imageid>
<imagetype/>
<image/>
<companyname>amit</companyname>
<description>sdfj</description>
<status>Not Sold</status>
<dou>2014-01-01</dou>
<like>0</like>
<price>123</price>
<color/>
</gal>
This is just an illustration and it works as shown.. Spoonfeeding is not good, so you try to explore more with this code..
<?php
$xml=' <ALLIMAGES>
<gal>
<imageid>6</imageid>
<imagetype>Vector</imagetype>
<image>..images/accept.png</image>
<companyname>w845</companyname>
<description>villain</description>
<status>sold</status>
<dou>2014-03-16</dou>
<like>22</like>
<price>212</price>
<color>BLUE</color>
</gal>
<gal>
<imageid>7</imageid>
<imagetype/>
<image/>
<companyname>amit</companyname>
<description>sdfj</description>
<status>Not Sold</status>
<dou>2014-01-01</dou>
<like>0</like>
<price>123</price>
<color/>
</gal>
</ALLIMAGES>';
$xml = simplexml_load_string($xml);
echo "<pre>";
echo "<form method='post' action=''>";
foreach ($xml->gal as $tag)
{
echo "Image ID : <input type='text' value=$tag->imageid />";echo "<br>";
echo "Company Name: <input type='text' value=$tag->companyname />";echo "<br>";
}
echo "</form>";
OUTPUT :

How to edit xml node value

I'm writing a custom plugin for use in my website using Jw player adtonomy plugin which loads adverts from XML files. However I do not know how to update the nodes in the files. I have tried using simple xml but I don't know how to update. Any implementation is highly regarded. Thanks. Here is the xml file.
<xml>
<plugins>adtimage</plugins>
<adtimage.graphic>http://mysite/default.png</adtimage.graphic>
<adtimage.link>http://targetsite.com</adtimage.link>
<adtimage.positions>pre,post</adtimage.positions>
<adtimage.onpause>true</adtimage.onpause>
<adtimage.txt>Advertisement</adtimage.txt>
<adtimage.btntxt>Click to continue with video</adtimage.btntxt>
</xml>
my code is here.
<?php
$xml = simplexml_load_file("test.xml");
echo $xml->getName() . "<br />";
foreach($xml->children() as $child)
{
echo $child->getName() . ": " . $child . "<br />";
/*
TO DO
change the node value of
<adtimage.graphic>http://mysite/default.png</adtimage.graphic>
to
<adtimage.graphic>http://stackoverflow.com</adtimage.graphic>
*/
}
?>
You can use this
//Load XML
$xml = simplexml_load_file("test.xml");
// Modify a node
$xml->{"adtimage.graphic"} = 'http://stackoverflow.com/adtimage.graphic';
// Saving the whole modified XML to a new filename
$xml->asXml('updated.xml');
Example Output 'updated.xml'
<?xml version="1.0"?>
<xml>
<plugins>adtimage</plugins>
<adtimage.graphic>http://stackoverflow.com/adtimage.graphic</adtimage.graphic>
<adtimage.link>http://targetsite.com</adtimage.link>
<adtimage.positions>pre,post</adtimage.positions>
<adtimage.onpause>true</adtimage.onpause>
<adtimage.txt>Advertisement</adtimage.txt>
<adtimage.btntxt>Click to continue with video</adtimage.btntxt>
</xml>

Parse XML in Js for Website

Hy!
I am very new in Web-Dev. I have a mysql db and the controller is made with PHP.
I give the data formated in php back to the html.
My Quest:
How to parse the xml in js right for the HTML based view?
If there are better solutions for the data transfair between PHP and HMTL, please let me know.
I don't wont the have HTML code in the php
Example PHP:
<?php
$id = $_GET['id'];
if (is_numeric($id))
{
include 'db_connect.php';
$sql = "Select * from RECIPES WHERE recipes_id=".$id;
$result = mysql_query($sql,$db) or exit("QUERY FAILED!");
while($row = mysql_fetch_array($result))
{
echo "<RECIPE>";
echo "<ID>" . $row['recipes_id'] . "</ID><br />";
echo "<TITLE>" . $row['text'] . "</TITLE><br />";
echo "<TEXT>" . $row['text'] . "</TEXT><br />";
echo "<COUNT_PERSONS>" . $row['count_persons'] . "</COUNT_PERSONS><br />";
echo "<DURATION>" . $row['duration'] . "</DURATION><br />";
echo "<USER_ID>" . $row['user_id'] . "</USER_ID><br />";
echo "<DATE>" . $row['date'] . "</DATE><br />";
echo "</RECIPE>";
}
}
else
{
echo "<ERROR>ID ERROR</ERRORR>";
}
mysql_close($db);
?>
thx
If you just want to transfer data between the browser and the server then it's simpler to use the JSON format. For PHP there are two built in function to decode and encode JSON: json_decode and json_encode.
Modern browser support JSON by default: JSON.parse and JSON.stringify.
I agree with styrr, but if you must use XML then you can use jQuery.parseXML() or simply use jQuery.ajax() with correct type eg.:
$.ajax({
url: "script.php?parameters=abc",
dataType: "xml",
success: function(responseDocument){
var all_ids = responseDocument.getElementsByTagName('ID');
var all_ids_jquery_way = $('ID', responseDocument);
}
});
You can use any othe AJAX framework or even write your own function. Browsers can parse XML and create a document which you can then change as the main document (with DOM functions).
Again with most data JSON is a bit simpler to use and is lighter.

Categories