PHP: Parse XML with SimpleXML - php

I'm having issues attempting to parse an XML file I'm pulling in from another site with SimpleXML. I need to display the rent for certain properties. However, I only want to display the rent for certain properties. I've never seen an XML file structured in this manner: http://dl.dropbox.com/u/1925679/example.xml
First, how would I parse through this file based on
Property->PropertyID->MITS:Identification->MITS:PrimaryID
Then, echo out the Property->Floorplan->MarketRent(Min and Max) based on an ID?
TIA!!!!

// get all properties
$properties = $xml->xpath('//Property');
// get document namesapces in prefix => uri format
$namespaces = $xml->getNamespaces(true);
foreach($properies as $property)
{
// get namespaced nodes
$identification = $property->PropertyID->children($namespaces['MITS']);
$id = $identification->children($namespaces['MITS'])->PrimaryID;
// do your check id is an expected value or whatever and if so then...
foreach($property->Floorplan as $floorplan){
{
echo $floorplan->MarketRent['min'];
echo $floorplan->MarketRent['max'];
}
}
You could probably com up with an xpath query to ONLY select properties with a given id or set of ids straight away so then you would only have to loop over them and invoke the floorplan loop but ill leave that to your investigation :-) I will say though if you go that route, you will need to register the namespaces with xpath i think. Pretty sure thats not automatic.

Related

Php retrieve XML elements and edit file on server

I've searched and tried a number of examples and answers I've found here, but I think my requirements are quite specific and I haven't been able to find an answer that's worked for me so far... Bodging a number of answers together hasn't worked either!
Aim - Update the hosplist_divert value of the same element that contains a specific name tag.
The XML file is hosted in a sperate folder to the php page, in those case at /data/hospitals2.xml
My XML is like so:
<Document>
<Placemark>
<name>UHSM Wythenshawe</name>
<hosplist_divert>1</hosplist_divert>
</Placemark>
</Document>
There are approx 50 Placemark entries in the file.
So far I am only able to return all the hospital names from the file with,
// Create the SXE object
// You can read from file using the simplexml_load_file function
$url = "http://www.patientpathfinder.co.uk/user/nwasdos/data/hospitals2.xml";
$sxe = new SimpleXMLElement($url, NULL, TRUE);
$sxe->registerXPathNamespace('hospital','http://earth.google.com/kml/2.2');
// Fetch the right HOSPITAL using XPATH
// hospital name stored in Document/Placemark/name
// dovert status stored in Document/Placemark/hosplist_divert
//trying to find above values for UHSM Wythenshawe
$result=$sxe->xpath('//hospital:name[.="UHSM Wythenshawe"]/parent::*');
foreach ($result as $hospital)
{
echo $hospital . "<br>";
}
// Update the values you want
//$target_hosp[0]->hosplist_divert = 'ON DIVERT';
// Store the updated values in the $xml variable
//$xml = $sxe->asXML();
// Print the updated XML
//echo $xml;
}
It took me about half a day to realise that I needed to define the namespace, but haven't really had time to understand why the namespace is required and would be happy to remove it from the XML file in. Favour of a working solution.
Thanks to all that contribute,
Nick

Zend get db data in xml format using context switching

i am curious to know how can i get the database data in xml format in Zend framework using context switching.
Do i need to compulsorily specify the format in my url, like:
http://localhost/pt/public/index.php/api/v1/users.xml?param1=3
I want to get the format from url (.xml, .json...) and apply the corresponding format to my output automatically.
Currently iam doing this: I get the user data from the database. I get the users marks based on the class id i pass to the url:
$id = $request->getParam('param1'); // get class id param
$users = new Application_Model_DbTable_Users();
$result = $users->fetchData($id);
if(count($result) != 0)
{
$doc = new DOMDocument();
$doc->formatOutput = true;
$root = $doc->createElement("Student");
$doc->appendChild($root);
foreach($result as $details)
{
$root_element = $doc->createElement("Marks");
$root->appendChild($root_element);
$TElement = $doc->createElement("Total");
$TElement->appendChild($doc->createTextNode($details->marks));
$root_element->appendChild($TElement);
}
$xml = $doc->saveXML();
$this->view->xml = $xml;
}
And in the corresponding view script, i have this code:
<?php
header('Content-type: text/xml');
echo $this->xml;
?>
I get the user data and use DOMDocument to write the xml output to the view. But is it possible to automatically generate the XML data from database, without using DOM ?
emaillenin is right, there's nothing ZF can do to convert your data to XML.
But instead of forming XML manually (with DOMDocument and the like), I suggest that you take a look at PEAR XML_Serializer package.
XML_Serializer allows you to transform arrays, objects, etc. to well-formed XML. You can also specify your root name, default tag names, indentation type, etc. So, you're pretty much in control for the resulting XML.
Zend context switching helps in changing your headers, disabling layout and those kind of helps. It does not help in returning the database data as XML data.
The following code can be used to return XML output once you have converted your DB data into XML formatted data with tags.
class OutputController extends Zend_Controller_Action
{
public function xmlAction()
{
$xml = simplexml_load_string($sourceData);
$output = $xml->saveXML();
Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->setNoRender(true);
$this->_helper->layout->disableLayout();
Zend_Layout::getMvcInstance()->disableLayout();
header('Content-Type: text/xml');
echo $output;
exit();
}
}
I will update the answer if you provide more information about how you retrieve the data from DB and what format of XML (the hierarchy of tags) you want in the output.

xml problem with php

I'm trying to use an xml file and retrieve all links from it. so far I have:
$xmlHeadline = $xml->channel[0]->item[3]->link;
print($xmlHeadline);
This works ok to print the single headline link for item[3] in the xml. But as you can see it is 2 levels deep. Then next one will be at channel[0]->item[4]->link. There is no channel 1, just channel[0].
All the examples on the internet only deal with 1 level deep. They all used a foreach loop, but I am not sure if that can be used here...
How can I cycle through all item's in the xml and echo all links?
Try
foreach ($xml->channel[0]->item as $item) {
echo $item->link;
}
or
foreach ($xml->xpath('/channel/item/link') as $link) {
echo $link;
}
I think you want a DOM parser, that will allow you to load the xml as a structured hierarchy and then use a function like getElementById http://php.net/manual/en/domdocument.getelementbyid.php to parse the xml and get the specific items you want at any depth.
If you provide the structure of the xml file I may be able to help with the specific use of a DOM function.
$str = '<channels><channel>
<item><link>google.com</link></item>
<item><link>google.com.cn</link></item>
<item><link>google.com.sg</link></item>
<item><link>google.com.my</link></item>
</channel></channels>';
$xml = simplexml_load_string($str);
$objs = $xml->xpath('//channel/item/link');
PS: Please include some example of your xml

php DOM, get values from xml document, php xml

I'm trying to get some information (itemID, title, price and mileage) for multiple listings from eBay website using their api. So far I got this up
I've saved the document as .xml file using PHP cUrl and now I need to get/extract the values(itemID, title, price and mileage) into arrays and store them in database.
Unfortunately I never worked with PHP DOM, and I can't figure out how to extract the values. I tried to follow the tutorial found on IBM website but I had no success. Some help would be highly appreciated.
Here is a code sample to get the ItemIDs from your XML file:
<?php
$doc = new DomDocument();
$doc->load('a.xml');
$response = $doc->getElementsByTagName('GetMultipleItemsResponse')->item(0);
$items = $doc->getElementsByTagName('Item');
foreach ($items as $item)
{
$itemID = $item->getElementsByTagName('ItemID')->item(0)->nodeValue;
echo $itemID."\n";
}
?>
$doc->getElementsByTagName() returns a DomNodeList. It can be used in a foreach loop, and it has an item() method.
A DomNodeList will contain all matching elements. If you know there is only one element, you can retrieve that with ->item(0)
The item() method returns a DomElement, which inherits from DomNode. DomNode has a nodeValue property, which contains the text within the element.
Summary: use SimpleXML

Updating the XML file using PHP script

I'm making an interface-website to update a concert-list on a band-website.
The list is stored as an XML file an has this structure :
I already wrote a script that enables me to add a new gig to the list, this was relatively easy...
Now I want to write a script that enables me to edit a certain gig in the list.
Every Gig is Unique because of the first attribute : "id" .
I want to use this reference to edit the other attributes in that Node.
My PHP is very poor, so I hope someone could put me on the good foot here...
My PHP script :
Well i dunno what your XML structure looks like but:
<gig id="someid">
<venue></venue>
<day></day>
<month></month>
<year></year>
</gig>
$xml = new SimpleXmlElement('gig.xml',null, true);
$gig = $xml->xpath('//gig[#id="'.$_POST['id'].'"]');
$gig->venue = $_POST['venue'];
$gig->month = $_POST['month'];
// etc..
$xml->asXml('gig.xml)'; // save back to file
now if instead all these data points are attributes you can use $gig->attributes()->venue to access it.
There is no need for the loop really unless you are doing multiple updates with one post - you can get at any specific record via an XPAth query. SimpleXML is also a lot lighter and a lot easier to use for this type of thing than DOMDOcument - especially as you arent using the feature of DOMDocument.
You'll want to load the xml file in a domdocument with
<?
$xml = new DOMDocument();
$xml->load("xmlfile.xml");
//find the tags that you want to update
$tags = $xml->getElementsByTagName("GIG");
//find the tag with the id you want to update
foreach ($tags as $tag) {
if($tag->getAttribute("id") == $id) { //found the tag, now update the attribute
$tag->setAttribute("[attributeName]", "[attributeValue]");
}
}
//save the xml
$xml->save();
?>
code is untested, but it's a general idea

Categories