Solved

Displaying PHP search results in XML document instead of simple HTML.

Posted on 2004-09-18
12
235 Views
Last Modified: 2013-11-19
I have a simple search form with two drop-down lists from where to select search criteria which are then processed by a separate php file. Results are rendered in html format by php file in the form of rows/columns (table). I need to display the html results in xml format which are in turn displayed accroding to xlst (.xsl) style sheet. I have xml file and xml schema (xsd) ready i.e well formed and valid. XSLT is rendering XML data as originally planned i.e in nice looking XHTML. Now I need to combine the two mechanisms. My problem is that I cannot find a way in outputting the php results directly to xml format which would then do the xlst transformation through  assigned .xsl file. Can anyone help please?
0
Comment
Question by:miamati
  • 6
  • 6
12 Comments
 
LVL 49

Expert Comment

by:Roonaan
ID: 12091240
What is not fully clear to me is if you have access to the php file and the output it gives. If so, it should be quite easy to change the output.

On the other side, you could write an extra php file which handles the html output and converts it to the xml you want, but this could be messy.

The easiest would be if you had access to the php file.
0
 

Author Comment

by:miamati
ID: 12091300
YES I have access to PHP and please also note that backend database is in MYSQL. The php code which handles the text input values is as follows:

<body">
      <?php

         extract( $_POST );
         $skill = $_POST['skill'];
         $level = $_POST['level'];
             
         $query = "SELECT first_name, last_name, email FROM users where ". $skill ." = '$level' ";
             // not empty: where ". $select ." >='1'
       
          if ( !( $database = mysql_connect( "localhost",
            "httpd", "" ) ) )
            die( "Could not connect to database" );
   
          if ( !mysql_select_db( "Agency", $database ) )
            die( "Could not open Agency database" );
   
          if ( !( $result = mysql_query( $query, $database ) ) ) {
            print( "Could not execute query! <br />" );
            die( mysql_error() );
         }
      ?>

<h1>Search Results</h1>

<p>Search Results</p>

     <table border = "1" cellpadding = "3" cellspacing = "2"
         style = "background-color: #E4E4E4">
             <tr>
            <td>Name </td>
            <td>Surname </td>
            <td>Email </td>
                       </tr>

        <?php

            // fetch each record in result set
            for ( $counter = 0;
               $row = mysql_fetch_row( $result );
               $counter++ ){

               // build table to display results
               print( "<tr>" );

               foreach ( $row as $key => $value )
                  print( "<td>$value</td>" );

               print( "</tr>" );
            }

            mysql_close( $database );
         ?>

      </table>
      </body>

As I told you I need to change the output to XML so I can use the XML for other purposes.
Thanks...
0
 
LVL 49

Expert Comment

by:Roonaan
ID: 12092184
I'll show an example of some xml file.

<?php
//output the xml header:
echo '<'.'?xml version="1.0">';
?>
<!-- replace this xmlcomment with the reference to your xml file-->
<searchresults>
      <?php

         extract( $_POST );
         $skill = $_POST['skill'];
         $level = $_POST['level'];
           
         $query = "SELECT first_name, last_name, email FROM users where ". $skill ." = '$level' ";
           // not empty: where ". $select ." >='1'
       
          if ( !( $database = mysql_connect( "localhost",
            "httpd", "" ) ) )
            die( "Could not connect to database</searchresults>" );
   
          if ( !mysql_select_db( "Agency", $database ) )
            die( "Could not open Agency database</searchresults>" );
   
          if ( !( $result = mysql_query( $query, $database ) ) ) {
            print( "Could not execute query!" );
            die(htmlspecialchars(mysql_error()).'</searchresults>');
         }
      ?>

<columns>
  <column name="Name" />
  <column name="Surname"/>
  <column name="Email"/>
</columns>
        <?php

            // fetch each record in result set
            for ( $counter = 0;
               $row = mysql_fetch_row( $result );
               $counter++ ){

               // build table to display results
               echo '<searchresult>';

               foreach ( $row as $key => $value )
                  echo '<'.$key.'>'.htmlspecialchars($value).'</'.$key.'>';

               echo '</searchresult>';
            }

            mysql_close( $database );
         ?>
</searchresults>

<!-- End of file -->

By example this will result in a xml file something like

<?xml version="1.0">
<?xml-stylesheet type="text/xsl" href="xslstylesheet.xsl"?>
<searchresults>
<columns>
  <column name="Name" />
  <column name="Surname"/>
  <column name="Email"/>
</columns>
<searchresult>
  <first_name>abel</first_name>
  <last_name>Smith</last_name>
  <email>theworks@dentist.com</email>
</searchresult>
<searchresult>
  <first_name>wakka</first_name>
  <last_name>contracta</last_name>
  <email>dawakka@dentist.com</email>
</searchresult>
</searchresults>

There might be some glitches in the coding, but it shouldn't take much to get this up and running.

-r-
0
 

Author Comment

by:miamati
ID: 12092558
It seems we're there....I have however added encoding="UTF-8"?> to solve trailing ? error. I could not figure out what I have to insert instead of <!-- replace this xmlcomment with the reference to your xml file-->. Is it reference to XML shcema (.xsd) or style sheet (.xsl) or it is not necessary for the time being? On outputting I am getting 'XML page cannot be displayed' error with a message 'Cannot view XML input using XSL style sheet...... and 'A name started with an invalid character. Error processing resource 'http://localhost/mysite/search.php.  Is XSL stylesheet needed at this point as I have not included any reference to stylesheets or schema and have removed all html tags i.e html/title/body? Thanks mate.
 
0
 
LVL 49

Expert Comment

by:Roonaan
ID: 12092594
the <!-- replace this .. etc was intended to be a pointer to your xsl file:

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

But i wasn't sure with the syntax, so i had to look it up at w3schools and forgot to replace it :-)

The problem I guess, could be lying in the fact we were using mysql_fetch_row.

mysql_fetch_row returns an array with numeric keys. So the xml output should look something like <0>Name</0><1>Last Name</1><2>Email</2>

If you replace mysql_fetch_row with mysql_fetch_assoc, things should work better as the keys will be the same as the fieldnames in your database and therefor the elements should be named as <first_name>, <last_name> and <email>.

I hope this will solve your problem, otherwise post bits of the outputted xml and we'll figure it out eventually ;-)

-r-
0
 

Author Comment

by:miamati
ID: 12094563
That was great! Output in XML is now just perfect and therefore _assoc did the trick. Last thing is that url on xml output still shows .php (search_php) extension at the end. Can I open it as xml document or when I apply xsl sheet it would be converted on the fly and therefore xml document (i.e .xml extension) is not shown? Thanks sir.
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 49

Accepted Solution

by:
Roonaan earned 500 total points
ID: 12094682
A way to trick your browsers is to linkt to the file in a fashion like:
search.php?q=etz&r=etc&ext=.xml

You then could add header('Content-type:text/xml'); to the top of your file to send out the correct 'filetype'.

There somewhere is a method to execute the xsl on the fly serverside, but I haven't worked with it yet, so I can't say things exactly.

www.php.net/xsl shows some methodology to do this. If you have/use php5 xslt support is available by default.

php.net/xsl shows the following example:

<?php
/* Load the two XML sources */
$xml = new DomDocument; // from /ext/dom
$xml->load('example.xml');

$xsl = new DomDocument;
$xsl->load('example.xsl');

/* Configure the transformer */
$proc = new xsltprocessor;
$proc->importStyleSheet($xsl); // attach the xsl rules
echo $proc->transformToXML($xml); // actual transformation
?>

If you'd like I could help/experiment  but it would be easier to know if you:
1. you want to execute the xslt serverside.
2. you then would realy want to use xml/xslt and not just through out the correct html
3. you have php5 available, or at least some xslt functionality (phpinfo() will tell you)

-r-
0
 

Author Comment

by:miamati
ID: 12096291
First of all thanks for your valuable assistance.....this should be my last query before I close and assign points ;-)
What I was thinking is that if I refer directly to my xsl stylesheet by echo '<'.'?xml-stylesheet type="text/xsl" href="emp_agency_stylesheet.xslt"?>'; I could use the xsl html redering on the fly!? In fact when I add the xsl declaration I manage to get the text heading which I have added on xsl stylesheet (as a sort of flag). This shows that style sheet residing on localhost web server (that's why xsi:noNamespaceSchemaLocation) is being fetched but no rows are displayed. Unfortunately I cannot use php5 as on project server they have ver. 4 so I thought I could manage doing the whole thing on the fly by uploading .xsd and .xslt on web server under site files. What do you think considering my situtation?

re xml extension problem you mean: action = "search.php?q=etz&r=etc&ext=.xml" in html file
echo 'Content-type:text/xml'; in php file before xml declaration? or use of echo is not applicable this way?
Thanks.
0
 
LVL 49

Expert Comment

by:Roonaan
ID: 12100057
When having php4 I think you just should stick by outputting a link to the stylesheet and letting the visitors browser do the work.
In php5 doing stuff on the fly would be an option, but could be a serious drain on your serversystem when files get to bulky.

for the 'Content-type:text/xml' you have to use the header() function. Echoing out will not do the trick, it just outputs the text Content-type:text/xml to the beginning of your actual output:

header('Content-type:text/xml'); //set the fileheader to say this is a xml file.

regards

-r-
0
 

Author Comment

by:miamati
ID: 12111568
Well I managed to transform xml using xsl though I still need to tweak up! Re header() function I am still getting .php on address bar and it seems that header function is being ignored. I will close question right away but in the meantime do you see any abnormality in the following xml declarations in my php file?

<?php
header('Content-type:text/xml');
echo '<'.'?xml version="1.0" encoding="UTF-8"?>';
echo '<'.'?xml-stylesheet type="text/xsl" href="xslstylesheet.xsl"?>';
?>

Thanks for all your help and guidance which were essential to me!
m
0
 
LVL 49

Expert Comment

by:Roonaan
ID: 12158247
Nothing wrong as far as I can tell.

Removing the .php from the url and still benefit from the php can only be done by changing some server settings and telling your server xml files are to be parsed by the php engine.

But you'd better not do that, because then you should check all your xml files and escape the '<?xml' piece in the code, to prevent parser errors.

-r-
0
 

Author Comment

by:miamati
ID: 12158980
ok thanks for your feedback....points already assigned!
m
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

Styling your websites can become very complex. Here I'll show how SASS can help you better organize, maintain and reuse your CSS code.
JavaScript has plenty of pieces of code people often just copy/paste from somewhere but never quite fully understand. Self-Executing functions are just one good example that I'll try to demystify here.
HTML5 has deprecated a few of the older ways of showing media as well as offering up a new way to create games and animations. Audio, video, and canvas are just a few of the adjustments made between XHTML and HTML5. As we learned in our last micr…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now