Zend get db data in xml format using context switching - php

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.

Related

Query XML from database and access DOM

The user creates a XML-file and stores it in the database as BLOB. Every XML-file gets its own row.
My script should query the Database and retrieve the XML-file of every row.
Every XML-file should be in an own php object and stored in an array. After that I need to access the DOM of every XML to display the data in an html template.
This is what I have got so far:
$stmt = $pdo->query('SELECT xml FROM table');
foreach ($stmt as $row)
{
echo $row['xml'] . "\n";
}
It will output the information without the xml-tags. I wonder why. The problem is, I somehow need to access the DOM.
I read about
simplexml_load_file
but it needs a filepath, which I don't have because the files are stored as BLOB in the DB.
Thank you!
You can use simplexml_load_string instead...
$stmt = $pdo->query('SELECT xml FROM table');
foreach ($stmt as $row)
{
$data = simplexml_load_string($row['xml']);
echo "<pre>".$data->asXML()."</pre>";
}
The reason why you probably don't see the tags is that you are echoing them out to a HTML page, which tries to interpret them as HTML tags.
Not sure about how your doing your foreach as it would more commonly be written as
while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) // Add correct retrieval method your after
{
$data = simplexml_load_string($row['xml']);
echo "<pre>".$data->asXML()."</pre>";
}
This depends on the API and if your using your own class methods though.

Sending XML file through PHP remote url

The situation is as follows. I have to send a defined XML to an url http:\\www.example.com:1234 with some variables that I have to previously define.
XML is like this:
<Title1>
<Title2>Some Text</Title2>
<Title3>Variable 1</Title3>
<Title4>Some Text</Title4>
<Title5>
<Title51>Variable 2</Title51>
</Title5>
</Title1>
But, I want to define those variables (1, 2) within an html/php form and get method, so the user can introduce both variables and then click on the submit button from the form to send the XML to the previously URL.
Also, XML should have the "Content-Type","application/x-www-form-urlencoded" header.
Is this possible? I've tried to pass these variables directly to the XML and the best that I've come to is to showing the XML and not parsing the php strings.
Also, I've tried some scripts like simplexml from PHP classes, but with no luck so far.
1) To modify existing XML with new values . Try this
sample.xml :
<Title1>
<Title2>Some Text</Title2>
<Title3>Variable 1</Title3>
<Title4>Some Text</Title4>
<Title5>
<Title51>Variable 2</Title51>
</Title5>
</Title1>
PHP :
$xml = simplexml_load_file("sample.xml");
$xml->Title3 = $_GET['t3']; // Updating <Title3></Title3> from GET method
$xml->Title5[0]->Title51 = $_GET['t5']; // Updating <Title51></Title51> from GET method
$xml->asXML('sample.xml'); // saving the xml file
2)To create new XML file (sample.xml) :
PHP:
$xml = new SimpleXMLElement("<Title1></Title1>");
$xml->Title2='Some Text';
$xml->Title3 = $_GET['t3'];
$xml->Title4='Some Text';
$xml->Title5[0]->Title51 = $_GET['t5'];
$xml->asXML('sample.xml'); // saving the xml file
I have showed you both possibilities mentioned in the comment . Use anyone which comforts you :)

PHP call a url returning XML/JSON

I am absolute beginner in PHP. Sorry for a very basic API question. I am stuck while coding at a point where I need to call a URL which will return me an XML or a JSON. Now I have to capture that in a variable.
For an example, I have written the following code:
class Search {
private $documents = array();
public function __construct() {
$xmlDoc = new DOMDocument();
$xmlDoc->load("solr.xml");
.....
Now I am directly loading an XML. I dont want to do that, instead:
Step1: I want to call a http url which returns me an XML or JSON.
Step2: I need to store that in some variable like xmlDoc above
Step3: and later ofcourse I want to parse it.
I have no issues with step 3 but I just need some pointers or help as to how can I accomplish step 1 and 2?
load should accept a URL as a parameter.
$xmlDoc = new DOMDocument();
$xmlDoc->load('http://example.com/path/to/file.xml');
Or, you can use file_get_contents to download a URL to a string.
$xml = file_get_contents('http://example.com/path/to/file.xml');
$xmlDoc = new DOMDocument();
$xmlDoc->loadXML($xml);
Or for JSON:
$json = json_decode(file_get_contents('http://example.com/path/to/file.json'));
For doing this with Json you first need a page which will have some json variables.
You can do this by yourself by typing:
$jsonVar = array('var1','var2'); // several variables
echo encode_json($jsonVar);
You can access these variables by typing:
$jsonUrl = 'http://example.com/json.php';
$jsonUrl = json_decode(file_get_contents($jsonUrl));
To display one of these variables you can type:
echo $jsonUrl[1]; // you can use print_r($jsonUrl); //for displaying the right array numbers to access the vars

PHP: Parse XML with SimpleXML

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.

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