Posted by: gbluma
on Jun 10, 2009
Every now and then I find myself needing to export a set of objects to XML. I usually find a quick way to write a dumb function to do it, but this is usually not the most elegant solution and rarely does it scale up to handle more complex data structures. The other option is to serialize the data into xml, but usually these methods suffer from a large performance overhead and should only be used if you can tweak the serializer to work only the right pieces of data.
I have since added XMLWriter to my toolset. Which, oddly enough, is built right into PHP (as of version 5.1.2) and based on the widely popular libxml engine. I find it to be very quick, both in performance and in ease of programming. Best of all, the code makes more sense than any of any of my own homemade tools.
Here's an example where demonstrate how to export a list of products to xml:
Posted by: twmeier
on Mar 2, 2009
While working on an AJAX function this week, I found the need to parse an XML string using JavaScript and PHP. The following JavaScript was used to retrieve an XML string from a PHP file:
function someJavascriptFunction() {
xmlHttp=GetXmlHttpObject();
url = "/components/com_component/ajax/ajax.php?task=someTask";
url += "&cc_number="+document.getElementById('cc_number').value;
xmlHttp.open("GET",url,true);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
xmlDoc=loadXMLString(xmlHttp.responseText);
var response = xmlDoc.getElementsByTagName("response")[0].childNodes[0].nodeValue;
document.getElementById("someID").innerHTML = response;
}
xmlHttp.send(null);
}
function GetXmlHttpObject() {
var xmlHttp=null;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e) {
//Internet Explorer
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
As you can see from the code above, the XML field I was interested in was the "response" field. The XML string that was created and passed using xmlHttp.responseText from the PHP file looked similar to this:
<authorizationResponse>
<message>Some Message</message>
<response>Some Message</response>
....
</authorizationResponse>
Not only did I need to parse the XML from the responseText in javascript, but I also need to parse it inside the PHP function that the JavaScript function called. The XML above was retrieved from a payment gateway in the PHP function using CURL and naned $xmlString.
The only field I needed in the PHP file was the "message" field, and to retrieve it, (or any other field), I did the following in the PHP file:
$xml = new SimpleXMLElement($xmlString);
$message = $xml->authorizationResponse->message;
Don't forget you still need to echo out the entire XML string in your PHP file order to be used by your JavaScript function:
echo $xmlString;