www.webdeveloper.com
Results 1 to 8 of 8

Thread: XML Request help needed

Hybrid View

  1. #1
    Join Date
    Sep 2012
    Posts
    3

    XML Request help needed

    Hi,

    i hope someone can help me with this. I have searched online but have not been able to figure out how to do this.

    We have a service URL (http://mysite.php) where we want to pull a list of titles from and display in on our homepage.

    I am limited to HTML components on the page because it is a CMS (sort of) and the only choices I have are HTML Component.

    The basic instructions I was given are these:

    Client will make a post request containing the field xmlreq. The value associated with that field will be as follows:

    <root>
    <client>{client code}</client>
    <request>publications</request>
    <request_id>{optional string which will be returned}</request_id>
    </root>

    The response returned will include all titles currently available to the client in the following format:

    <root>
    <client>{client code}</client>
    <request_id>{optional string passed in request}</request_id>
    <response_time>{date and time response was created as a GMT time in the format yyyymmddhhmmss}</response_time>
    <status>{0 or 1}</status>
    <msg>{optional message}</msg>
    <pubs>
    <pub>
    <pub_id>{unique assigned 32 character string}</pub_id>
    <pub_name>[<![CDATA[{publication name}]]><pub_name>
    <categories>
    <category><![CDATA[category name]]></category>
    </categories>
    </pub>
    </pubs>
    </root>

    If the post was successful, the status element will be 0 and the msg element will be blank. If the post was unsuccessful, the msg element will be 1 and the msg element will contain a description of the error(s).

    How can I format this request into HTML? and incluie the required fields?

    Any help is appreciated!

    Thanks,

    Russ

  2. #2
    Join Date
    Jul 2010
    Posts
    66
    This seems like you are asking for using XSLT + XPath. I am just getting into this myself as a beginner. You might be familiar with this already (?) but the basic operation goes like this:

    1. You create the XML document (xldoc #1) response as you have above
    2. You now need to create a separate XML document (xldoc #2) representing the stylesheet (XSLT)
    3. The HTML markup will be contained in an <xsl-template> element of the XSLT document
    4. (a) Within the xldoc #2 <xsl-template> contained text, you insert XSLT elements which are basically functions that retrieve elements, their attributes, or more importantly, the contained text (PCDATA) in xldoc #2
    (b) You may need to learn a limited subset of XPath expressions as well to retrieve sequences (collections of object nodes) which you manipulate to get elements, attributes, and contained text
    5. Specify in the URI within xldoc #1 which points to xldoc #2 as being its stylesheet, and it will be rendered as HTML upon delivery to the client

    Books (as PDFs) that I am reading now with this info are:

    * Watt, XPath Essentials (Wiley, 2002)
    * Ian Williams, Beginning XSLT and XPath (Wrox, 2009)

    message me if you want pointers on this and other books

    I recommend you use this approach, while there may be other approaches too. Learning XSLT transforms and XPath (probably within a few days to a week) will serve you well, I am guessing

  3. #3
    it makes some sense, so do you have any code through which I can do this, means I know how to set the header eg. xhr.setRequestHeader("",""), but which attributes should I supply.

  4. #4
    Join Date
    Jul 2010
    Posts
    66
    I am not sure why you need the XML Http request object at this point (probably later).

    You want to render your XML file as HTML, right?

    You only need two files: your XML file/document, which you already have, and the XSLT file which you need to make

    To show you how this is done, go to this page and scroll down to the XML + XSLT header (with light yellow background color).

    Copy and paste the rec.xml part into your new text file and save as 'rec.xml' into any directory of your server
    Copy and paste the rec.xsl part into its own new text file and save as 'rec.xsl' in the same directory as your rec.xml.
    [Make sure all XML-type files (*.xml or *.xsl) start on line 1 and column 1, or I think you get XML parsing errors in the browsers.]

    1. Now enter into a browser (IE, FF, etc) in the address bar "http://myserver.xxx/path/to/rec.xml"

    You see the XML file in HTML form

    2.. Now go to the rec.xml file, comment out (using <!-- .... -->) the part that says

    <?xml-stylesheet href="rec.xsl" type="text/xsl"?>

    Reload your rec.xml file in your browser. No more HTML format, but rather raw XML presentation.

    What you need to do now:

    1. Draw up your HTML code as you would want it to look in your presentation. If you have a multi-record XML document, just use one of the records (the field/column data in it) as an example of how you want it to look. This is the longest hardest part...getting it the way you want it to look. This part will go into the <xsl:template> element of your XSLT (*.xsl) document.

    2. Now you need to make the XSLT (*.xsl) document. This means you need to learn about at least 12-13 important "top level" <xsl:xxxx> elements. These elements help you to insert XML data into the <xsl:template> element from your XML file. For instance if you want to make an HTML <table> of the the multiple XML records, there is a top level element <xsl:for-each> that will help you get the records and their fields and place them where you want. If you are familiar with PHP+MySQL, this is basically the retrieval-and-insert/place processing you use to make a report of your XML or MySQL-as-database setup.

    The example above shows you just how *.xsl files work with *.xml files to present whatever you want. The info you are missing is in the two easily obtained books I cited.

    There is no need for Ajax at this time, unless you want to use it import additional stuff, and you would find a way to put it into the XSTL document. since I have no experience working with Ajax inside XSLT, your best bet is to google to see someone who has done it and shows an example.
    Last edited by seniseven; 09-22-2012 at 12:33 AM.

  5. #5
    Join Date
    Jul 2010
    Posts
    66
    I want to add something about your XML request object part.

    Suppose your records are in 'myfile.xml'. Check that the xml validates against a validator

    Format your Ajax request as a GET to your 'myfile.xml'

    I think that is straightforward, but it might go something like this:

    Code:
    // 'var' declarations omitted, but use them
    responseHandler = function () {
    /* checks request status for COMPLETE
       get the responseText or responseXML properties and
       work with them...return back to main threads of execution
       consider defining and using asynchronous callbacks */
    };
    xmlReqObj = new XMLHttpRequest(); // might be ActiveXObject if Windows
    xmlReqObj.overrideMimeType("text/xml");
    method = "GET";
    url = "http://server.xxx/path/to/myfile.xml";
    isAsynchronousRequest = false;
    xmlReqObj.onreadystatechange = responseHandler;
    xmlReqObj.open(method, url, isAsynchronousRequest);
    // if using a POST method, you will want to compute the POST string length
    // and then set request header as follows:
    // xmlReqObj.setRequestHeader("Content-Length", lengthInBytesOfPostData);
    xmlReqObj.setRequestHeader("Connection", "close"); // probably not necessary
    // Note only make .setRequestHeader() method calls AFTER the .open() method call
    //    I learned this the hard way
    
    xmlReqObj.send(null);  // for GET requests
    // for POST requests:  xmlReqObj.send(formData);
    In the request object RESPONSE is the property .responseXML (the other is .responseText). If your XML file validates, the .responseXML property contains a document object which is a tree of DOM nodes for your entire document. If .responseXML property is null, you have an invalid XML file...fix it and try again.

    In the client, use Javascript to call DOM methods on the .responseXML property, being an object to retrieve the node(s), its/their attributes, and the contained text (you can .normalize all text nodes and retrieve text nodes with DOM methods). These DOM methods and properties would be getElementsByTagName(), getElementsById(), firstChild, lastChild, nextSibling, etc. Take the retrieved node data of all types (element, attribute, text), and insert it into the HTML DOM tree where you wish it to be, changing your HTML document.

    Be sure to check all code in multiple browsers and especially earlier versions of IE if you think this will be an issue. Install several virtual machines with older versions of Windows (Win 95/98, WinXP) and their versions of IE, then see what you see.
    Last edited by seniseven; 09-22-2012 at 01:25 AM.

  6. #6
    Join Date
    Sep 2012
    Posts
    3

    more information

    Hi,

    I am very much a beginner.

    The problem I have is that I need to embed the XML in a single HTML document. We have a CMS (Like Drupal) that is only customizable using HTML component add ons. to make it more difficult the CMS does not understand PHP embedded in HTML...

    I was giving the following php code that would work to query the server and return the results but I am having trouble translating this to XML.

    They suggested using the REStClient add on for Firefox and I have been trying to build my request that way.

    If someone could convert this PHP into a workable REST request I believe I could then embed this in the HTML

    #!/usr/bin/php
    <?php

    /*

    test program to retrieve documents

    */

    // request data
    $client_code = 'e20d0b74030fad8a9b239ddf6bb4fb55'; // ABC Firm client code
    $request_id = 'Optional string: Test request';
    $request = 'publications';

    $url = 'http://companyname.services.php';

    $template = <<< EOH
    <root>
    <client>{CLIENT_CODE}</client>
    <request>{REQUEST}</request>
    <request_id>(REQUEST_ID}</request_id>
    </root>
    EOH;

    $data = str_replace("{CLIENT_CODE}", $client_code, $template);
    $data = str_replace("{REQUEST}", $request, $data);
    $data = str_replace("{REQUEST_ID}", $request_id, $data);

    $fields_count = 1;
    $parms = "xmlreq=$data";

    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL, $url);
    curl_setopt($ch,CURLOPT_POST, $fields_count);
    curl_setopt($ch,CURLOPT_POSTFIELDS, $parms);
    $result = curl_exec($ch);

    print "$result\n";

    ?>

    Thanks so much

    Russ

  7. #7
    Join Date
    Jul 2010
    Posts
    66
    Quote Originally Posted by rjr19146 View Post
    I was giving the following php code that would work to query the server and return the results but I am having trouble translating this to XML.
    You say you were "given" this PHP code. Who gave it to you?

    CMS implementations like Drupal are written in PHP, although they can certainly transfer control to other PHP scripts too in the course of Drupal working. I am no expert on using CMS in general (I write my own basically) and Drupal in particular. Perhaps whoever gave you this PHP code was giving you what Drupal called a "snippet," something I found after doing a google search to see if Drupal would permit running PHP code "on the side." It appears that Drupal allows you to incorporate "snippets" which extend functionality of Drupal, and perhaps give you what you want. I suppose the ability to incorporate snippets is described here:

    http://drupal.org/node/337959

    For snippets in PHP code to be run in Drupal:

    http://drupal.org/node/1288700

    That document should explain how to work the PHP snippet you have below, assuming it is correctly coded by whomever gave it to you.

    In another direction, I also know nothing about REST clients or the REST protocol, although I did a quick look at its Wikipedia entry and also at the FF addon. From the screenshots of the FF addon REST client, it will allow you to interact with the server so long as your server incorporates REST functionality---I am guessing that Drupal can provide that functionality within its package so long as you call the correct PHP document that provides the form or the protocol. The client appears to allow you to build three essential parts to a REST request: the method, the header, and the body. Since the body appears full of XML markup, that is probably where you want to put your XML in. You may need to learn something about how to properly format or build a REST body content.

    Let me show you what is happening in the PHP code you were given. I will use valid PHP commenting to show you what happens in its execution sequence:

    PHP Code:
    <?php

    /*

    test program to retrieve documents

    */

    /*  you have 3 data items:
     1. client code
     2.  request id
     3.  request

    Three PHP variables (a PHP variable is always understood by the 1st character being '$')
    are initialized with the strings shown.  A string is a set of character bound by either single-quote
    or double-quote characters (both are valid).  All PHP statements end in a semicolon (;)
    Comments in PHP are indicated by a '//' set of characters, in which text after that is comment
    up to the end of the line.  All text between 'slash-asterisk' and 'asterisk-slash' (w/o the quotes) is also not-to-be interpreted comments....I had to write slash-asterisk and asterisk-slash or the commenting would be affected
    */

    // request data
    $client_code 'e20d0b74030fad8a9b239ddf6bb4fb55'// ABC Firm client code
    $request_id 'Optional string: Test request';
    $request 'publications';

      
    // another string to variable 'url' is set, obviously a URL
    $url 'http://companyname.services.php';

    /* the variable 'template' is initialized to the string between the EOH...EOH delimiters.
        That is $template is set to a string having XML markup, and it includes newline characters
        wherever you see line breaks.  XML does not necessarily require that markup be broken into newlines */
    $template = <<< EOH
    <root>
    <client>{CLIENT_CODE}</client>
    <request>{REQUEST}</request>
    <request_id>{REQUEST_ID}</request_id>  
    </root>
    EOH;

    // HUGE NOTE:  the part "(REQUEST_ID}" has been changed to "{REQUEST_ID}" or the rest of the PHP code
    // will not execute properly

    /* the PHP function str_replace() "string replace" is used to build-up the PHP variable 'data'
       explanation of how function works:  http://php.net/manual/en/function.str-replace.php  */
    $data str_replace("{CLIENT_CODE}"$client_code$template);
    // $data = "<root>\n<client>e20d0b74030fad8a9b239ddf6bb4fb55</client>\n<request>{REQUEST}</request>\n<request_id>(REQUEST_ID}</request_id>\n</root>"
    $data str_replace("{REQUEST}"$request$data);
    // $data = "<root>\n<client>e20d0b74030fad8a9b239ddf6bb4fb55</client>\n<request>publications</request>\n<request_id>(REQUEST_ID}</request_id>\n</root>"
    $data str_replace("{REQUEST_ID}"$request_id$data);
    // $data = "<root>\n<client>e20d0b74030fad8a9b239ddf6bb4fb55</client>\n<request>publications</request>\n<request_id>Optional string: Test request</request_id>\n</root>"

    /*  Set up for using the cURL interface.  This allows PHP to get on the Internet and use TCP/IP services to get documents.  For more information:  http://php.net/manual/en/book.curl.php  */


    $fields_count 1;   // used in setting the cURL HTTP POST method option
    $parms "xmlreq=$data";  // that $data variable above is used to set the $parms variable as a string
    /* $parms now has the value of the string:
    "xmlreq=<root>\n<client>e20d0b74030fad8a9b239ddf6bb4fb55</client>\n<request>publications</request>\n<request_id>Optional string: Test request</request_id>\n</root>"
    */

    $ch curl_init();  // a necessary initialization of the cURL module
    curl_setopt($ch,CURLOPT_URL$url);  // tell it what your URL is
    curl_setopt($ch,CURLOPT_POST$fields_count);  // set up the required HTTP POST method conditions
    curl_setopt($ch,CURLOPT_POSTFIELDS$parms); // give it the HTTP POST content
    $result curl_exec($ch);  // send the HTTP POST request and wait for the HTTP POST response and put it in $result

    print "$result\n";
    /*  this sends to the browser screen your HTTP POST response (formatted?)
     I think the command 'echo' is used by most coders however. */

    ?>
    Note that everything that was a comment was orange-colored. Everything that was a string was red-colored, green-colored stuff are delimiters, and blue-colored stuff is PHP-recognized identifiers (variables) or functions or special variables. Note that 'print' was green colored...perhaps 'echo' would have been better.
    Last edited by seniseven; 09-28-2012 at 05:48 AM.

  8. #8
    Join Date
    Sep 2012
    Posts
    3

    Thanks!

    Thanks for the quick response and the the detailed explanation of the PHP code.

    the code was givent to me from one of our vendors. This is the company from where I want to pull the list of publications.

    The CMS we use is not Drupal though but is the Web diplay part of a library system. That is why I am so limited in what I can use. The library system lies on top of our company intranet so in order to have the list of documents retrieved into the library system I am limited to HTML or XML. I think with your break down of the code I can possibly re write this as an XML request although I am havin trouble with some of the syntax.

    Thanks again. If I am unable to get this to work within the library system I may try to have a separate page on the intranet where PHP could be used.

    Thanks!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles