Solved

Complicated pagination and data listing

Posted on 2011-09-06
30
430 Views
Last Modified: 2013-12-13
requirement
I need to display the column on the right with pagination.

Every company has an listid like, http://www.website.com/getbranch.php?listid=12345 and to check whether this company have a branch I:

SELECT * FROM customer_branch WHERE Branch='1' AND LISTING_ID = $listid
0
Comment
Question by:rolandmy
  • 16
  • 14
30 Comments
 
LVL 17

Expert Comment

by:OmniUnlimited
Comment Utility
I use the following code for pagination:
 
function show_pages($pages, $link_url, $curpage, $show_word=true) {
    // shows page numbers
    $output = "<div class='page_numbers'>\n\r";
    $output .= "<span class='flatview'>\n\r";
	if ($curpage > 1) {
	  	$prev = $curpage - 1;
	    $output .= "<a href='".$link_url."&page_number=$prev' >&laquo;";
		if ($show_word) { $output .= " Prev"; }
		$output .= "</a>\n\r";
	}
    for($i=1;$i<=$pages;++$i) {
      if ($curpage == $i) {
        if($_GET['view_all'] != 'true') {
          $selected = "class='selected'";
		} else {
    	  $selected = "class='notselected'";
	  	}
	  } else {
         $selected = "class='notselected'";
	  }
	  if ($i > 1) {
		 if ($pages > 13) {
				if ($curpage > 7) {
					if ($i == 3) {
						$output .= '...&nbsp;';
						continue;
					}
					if ($curpage < $pages - 7) {
						if ($i < 3) {
							$output .= "  <a href='".$link_url."&page_number=$i' $selected >$i</a>\n\r";
							continue;
						}
						if ($i < $curpage - 3) {
							continue;
						}
						if (($i > $curpage + 3) && ($i < $pages - 2)) { 
							continue; 
						}
						if ($i == $pages - 2) {
							$output .= '...&nbsp;';
							continue;
						}
					} else {
						if ($i < 3) {
							$output .= "  <a href='".$link_url."&page_number=$i' $selected >$i</a>\n\r";
							continue;
						}
						if ($i < $pages - 9) {
							continue;
						}
					}
				} else {
					if (($i > 10) && ($i < $pages - 2)) { 
						continue; 
					}
					if ($i == $pages - 2) {
						$output .= '...&nbsp;';
						continue;
					}
				}
			}
		}
      $output .= "  <a href='".$link_url."&page_number=$i' $selected >$i</a>\n\r";
	}    
	if ($curpage < $pages) {
	  	$next = $curpage + 1;
	    $output .= "<a href='".$link_url."&page_number=$next' >";
		if ($show_word) { $output .= "Next "; }
		$output .= "&raquo;</a>\n\r";
	}
    $output .= "</span>\n\r";
    $output .= "</div>\n\r";
	return $output;
}

Open in new window


To utilize it, simply define some of the following variables:
 
$url = "http://www.website.com/getbranch.php?listid=12345";
         $sql = "SELECT * FROM customer_branch WHERE Branch='1' AND LISTING_ID = $listid";
         if (!$tbl = mysql_query($sql))
         {
             $errmsg = mysql_errno() . ' ' . mysql_error();
             echo "<br/>QUERY FAIL: ";
             echo "<br/>$sql <br/>";
             die($errmsg);
         }
 	$max_lines = 20;
	$total_rec = count($tbl);
	$pages = ceil($total_rec / $max_lines);
	$item_no = 0;
	$line_no = 0;
	if(isset($_GET['page_number'])) {	
		$curpage = $_GET['page_number'];
	} else {
		$curpage = 1;
	}
	$start = (($curpage - 1) * $max_lines) + 1;
	if ($pages > 1) {
		$end = $start + $max_lines - 1;
		if ($end > $total_rec) { $end = $total_rec; }
		echo "<div class='tablenav-pages'>";
		echo "<span class='displaying-num'>";
		echo "Displaying " . $start . "-" . $end . " of " . $total_rec;
		echo "</span>";
		echo show_pages($pages, $url, $curpage, false);
		echo "</div>";
	}
	foreach($tbl as $row) {
		$item_no++;
		if ($item_no < $start) { continue; }
		$line_no++;
		if ($line_no > $max_lines) { break; }
                  // your code to display the list
         }

Open in new window

0
 
LVL 2

Author Comment

by:rolandmy
Comment Utility
Original code:

<?php

include("../connection.php");

$listingid = $_GET["ListingID"];

$result = connect("SELECT * FROM customer_branch WHERE Branch='1' AND LISTING_ID = $listingid","central");
      
echo '<?xml version="1.0" encoding="UTF-8"  standalone="no" ?>';
echo '<Branches>';

While($row = mysql_fetch_array($result))
{
      echo '<Listings>';
      echo '<LISTING_ID>'.$row["LISTING_ID"].'</LISTING_ID>';
      echo '<BRANCH_NAME>'.htmlentities($row["BRANCH_NAME"], ENT_QUOTES).'</BRANCH_NAME>';
      echo '<ADDRESS>'.htmlentities($row["ADDRESS"], ENT_QUOTES).'</ADDRESS>';
      echo '<AREA_CODE_Main>'.$row["AREA_CODE_Main"].'</AREA_CODE_Main>';
      echo '<TELEPHONE_Main>'.$row["TELEPHONE_Main"].'</TELEPHONE_Main>';
      echo '<Mobile_Area_M>'.$row["Mobile_Area_M"].'</Mobile_Area_M>';
      echo '<MOBILE_M>'.$row["MOBILE_M"].'</MOBILE_M>';
      echo '<ANTH_TELEPHONE_AREACODE>'.$row["ANTH_TELEPHONE_AREACODE"].'</ANTH_TELEPHONE_AREACODE>';
      echo '<ANTH_TELEPHONE_PHONE>'.$row["ANTH_TELEPHONE_PHONE"].'</ANTH_TELEPHONE_PHONE>';
      echo '<FAX_Area_Code>'.$row["FAX_Area_Code"].'</FAX_Area_Code>';
      echo '<FAX_Area_Phone>'.$row["FAX_Area_Phone"].'</FAX_Area_Phone>';
      echo '<URL>'.$row["URL"].'</URL>';
      echo '</Listings>';
}
echo '</Branches>';
?>
0
 
LVL 2

Author Comment

by:rolandmy
Comment Utility
Hi Omniunlimited, how do you just display the column on the right as shown in the picture? Please ignore the column on the left.
0
 
LVL 17

Expert Comment

by:OmniUnlimited
Comment Utility
You would just place my show_pages function where you have the rest of your site's functions and modify your code to look something like this:

<?php

include("../connection.php");

$listingid = $_GET["ListingID"];

$url = "http://www.website.com/getbranch.php?listid=12345";
$result = connect("SELECT * FROM customer_branch WHERE Branch='1' AND LISTING_ID = $listingid","central");
      
echo '<?xml version="1.0" encoding="UTF-8"  standalone="no" ?>';
echo '<Branches>';

$max_lines = 20;
$total_rec = count($tbl);
$pages = ceil($total_rec / $max_lines);
$item_no = 0;
$line_no = 0;
if(isset($_GET['page_number'])) {	
	$curpage = $_GET['page_number'];
} else {
	$curpage = 1;
}
$start = (($curpage - 1) * $max_lines) + 1;
if ($pages > 1) {
	$end = $start + $max_lines - 1;
	if ($end > $total_rec) { $end = $total_rec; }
	echo "<div class='tablenav-pages'>";
	echo "<span class='displaying-num'>";
	echo "Displaying " . $start . "-" . $end . " of " . $total_rec;
	echo "</span>";
	echo show_pages($pages, $url, $curpage, false);
	echo "</div>";
}
While($row = mysql_fetch_array($result))
{
      $item_no++;
      if ($item_no < $start) { continue; }
      $line_no++;
      if ($line_no > $max_lines) { break; }
      echo '<Listings>';
      echo '<LISTING_ID>'.$row["LISTING_ID"].'</LISTING_ID>';
      echo '<BRANCH_NAME>'.htmlentities($row["BRANCH_NAME"], ENT_QUOTES).'</BRANCH_NAME>';
      echo '<ADDRESS>'.htmlentities($row["ADDRESS"], ENT_QUOTES).'</ADDRESS>';
      echo '<AREA_CODE_Main>'.$row["AREA_CODE_Main"].'</AREA_CODE_Main>';
      echo '<TELEPHONE_Main>'.$row["TELEPHONE_Main"].'</TELEPHONE_Main>';
      echo '<Mobile_Area_M>'.$row["Mobile_Area_M"].'</Mobile_Area_M>';
      echo '<MOBILE_M>'.$row["MOBILE_M"].'</MOBILE_M>';
      echo '<ANTH_TELEPHONE_AREACODE>'.$row["ANTH_TELEPHONE_AREACODE"].'</ANTH_TELEPHONE_AREACODE>';
      echo '<ANTH_TELEPHONE_PHONE>'.$row["ANTH_TELEPHONE_PHONE"].'</ANTH_TELEPHONE_PHONE>';
      echo '<FAX_Area_Code>'.$row["FAX_Area_Code"].'</FAX_Area_Code>';
      echo '<FAX_Area_Phone>'.$row["FAX_Area_Phone"].'</FAX_Area_Phone>';
      echo '<URL>'.$row["URL"].'</URL>';
      echo '</Listings>';
}
echo '</Branches>';
?>

Open in new window

0
 
LVL 2

Author Comment

by:rolandmy
Comment Utility
Added the function into connection.php but not paginated...the result is as below.

108756CUSTOMER ONE BEACH RESORT & SPA
Lot 1698, Pantai Tengah, Mukim Kedawang, Hong Kong.
04952999904955150499.7327586.273637reservation@lgkhvl.com108756CUSTOMER ONE BEACH RESORT & SPA CHERATING
Lot 1303, Mukim Sungai Karang, 26080, Hong Kong
095819500095819178102.9521324.028876saleschv@hongkong.net108756CUSTOMER ONE HOTEL & SUITES SUBANG
9, Jalan SS 12/1, 47500, Hong Kong
03563387880356337449101.5978063.078994reservation@hongkongsubang.net108756CITY VILLA KUALA LUMPUR
69, Jalan Haji Hussein, Hong Kong.
03269260770326927734101.699353.165044 mayorsale@hongkong.net108756CUSTOMER ONE HOTEL & SUITES ALOR STAR
Lot 162,163, Jalan Tunku Ibrahim, Hong Kong.
047349999047341199100.3700636.117893reservation@hongkong.net108756TUAN CHAU ISLAND CUSTOMER ONE HALONG BAY, VIETNAM
Tuan Chau Island, Ha Long City, Quang Ninh Province, Vietnam
084333842999843338423106.98809120.934079info@tuanchauresort.com.vn108756WINA CUSTOMER ONE KUTA BALI
JL. Pantai Kuta, Bali 80361-Indonesia
62361753063623617515115.174414-8.722514winahvsales@hongkong.net108756DIWANGKARA CUSTOMER ONE BEACH RESORT & SPA BALI
J1. Hangtuah No. 54, P.O. Box 3120 Denpasar Sanur Beach, Bali, Indonesia
62361288577623612888115.263113-8.674544dhvbali@indosat.net.id108756CUSTOMER ONE HOTEL & SUITES PHNOM PENH
89 Monivong Boulevard, Sangkat Monorom Khan, 7 Makara, Phnom Penh, The Royal Kingdom of Cambodia. (Po
855239908888552399099104.91821511.570497monoromsales@camnet.com.kh108756CUSTOMER ONE HOTEL & RESIDENCE CITY CENTRE DOHA
P.O. Box 47601 Al-Muntazah, Doha, Qatar
9744084888974408400851.51762225.271958info@hongkongdoha.com
0
 
LVL 2

Author Comment

by:rolandmy
Comment Utility
I changed the

$max_lines = 5;

only 5 results came out but no pagination...
0
 
LVL 17

Expert Comment

by:OmniUnlimited
Comment Utility
Did you upload the show_pages function and are you sure that your code is accessing it?
0
 
LVL 2

Author Comment

by:rolandmy
Comment Utility
Yes, I just double checked. I added the function show_pages($pages, $link_url, $curpage, $show_word=true) in the connection.php, at the bottom.

0
 
LVL 17

Expert Comment

by:OmniUnlimited
Comment Utility
Sorry, I looked at your code again.  You are creating an XML, not HTML.

Try this:

<?php

include("../connection.php");

$listingid = $_GET["ListingID"];

$url = "http://www.website.com/getbranch.php?listid=12345";
$result = connect("SELECT * FROM customer_branch WHERE Branch='1' AND LISTING_ID = $listingid","central");
      
$max_lines = 20;
$total_rec = count($tbl);
$pages = ceil($total_rec / $max_lines);
$item_no = 0;
$line_no = 0;
if(isset($_GET['page_number'])) {	
	$curpage = $_GET['page_number'];
} else {
	$curpage = 1;
}
$start = (($curpage - 1) * $max_lines) + 1;
if ($pages > 1) {
	$end = $start + $max_lines - 1;
	if ($end > $total_rec) { $end = $total_rec; }
	echo "<div class='tablenav-pages'>";
	echo "<span class='displaying-num'>";
	echo "Displaying " . $start . "-" . $end . " of " . $total_rec;
	echo "</span>";
	echo show_pages($pages, $url, $curpage, false);
	echo "</div>";
}

echo '<?xml version="1.0" encoding="UTF-8"  standalone="no" ?>';
echo '<Branches>';

While($row = mysql_fetch_array($result))
{
      $item_no++;
      if ($item_no < $start) { continue; }
      $line_no++;
      if ($line_no > $max_lines) { break; }
      echo '<Listings>';
      echo '<LISTING_ID>'.$row["LISTING_ID"].'</LISTING_ID>';
      echo '<BRANCH_NAME>'.htmlentities($row["BRANCH_NAME"], ENT_QUOTES).'</BRANCH_NAME>';
      echo '<ADDRESS>'.htmlentities($row["ADDRESS"], ENT_QUOTES).'</ADDRESS>';
      echo '<AREA_CODE_Main>'.$row["AREA_CODE_Main"].'</AREA_CODE_Main>';
      echo '<TELEPHONE_Main>'.$row["TELEPHONE_Main"].'</TELEPHONE_Main>';
      echo '<Mobile_Area_M>'.$row["Mobile_Area_M"].'</Mobile_Area_M>';
      echo '<MOBILE_M>'.$row["MOBILE_M"].'</MOBILE_M>';
      echo '<ANTH_TELEPHONE_AREACODE>'.$row["ANTH_TELEPHONE_AREACODE"].'</ANTH_TELEPHONE_AREACODE>';
      echo '<ANTH_TELEPHONE_PHONE>'.$row["ANTH_TELEPHONE_PHONE"].'</ANTH_TELEPHONE_PHONE>';
      echo '<FAX_Area_Code>'.$row["FAX_Area_Code"].'</FAX_Area_Code>';
      echo '<FAX_Area_Phone>'.$row["FAX_Area_Phone"].'</FAX_Area_Phone>';
      echo '<URL>'.$row["URL"].'</URL>';
      echo '</Listings>';
}
echo '</Branches>';
?>

Open in new window

0
 
LVL 2

Author Comment

by:rolandmy
Comment Utility
Still no pagination...need to be like the image i provided in my first posting.

$hq is 1 result which is in the first page. $result have 15 results, which should be in the second page due to them being the branches to $hq.

Below are my code:

<?php

include("../connection.php");

$listingid = $_GET["ListingID"];

$url = "http://website.com/list.php?ListingID=$listingid";
$hq = connect("SELECT * FROM customer_branch WHERE Branch='0' AND LISTING_ID = $listingid","central");
$result = connect("SELECT * FROM customer_branch WHERE Branch='1' AND LISTING_ID = $listingid","central");
     
$max_lines = 5;
$total_rec = count($tbl);
$pages = ceil($total_rec / $max_lines);
$item_no = 0;
$line_no = 0;
if(isset($_GET['page_number'])) {      
      $curpage = $_GET['page_number'];
} else {
      $curpage = 1;
}
$start = (($curpage - 1) * $max_lines) + 1;
if ($pages > 1) {
      $end = $start + $max_lines - 1;
      if ($end > $total_rec) { $end = $total_rec; }
      echo "<div class='tablenav-pages'>";
      echo "<span class='displaying-num'>";
      echo "Displaying " . $start . "-" . $end . " of " . $total_rec;
      echo "</span>";
      echo show_pages($pages, $url, $curpage, false);
      echo "</div>";
}

echo '<?xml version="1.0" encoding="UTF-8"  standalone="no" ?>';
echo '<Branches>';

While($row = mysql_fetch_array($hq))
{
      $item_no++;
      if ($item_no < $start) { continue; }
      $line_no++;
      if ($line_no > $max_lines) { break; }
        echo '<Listings>';
        echo '<LISTING_ID>'.$row["LISTING_ID"].'</LISTING_ID>';
        echo '<BRANCH_NAME>'.htmlentities($row["BRANCH_NAME"], ENT_QUOTES).'</BRANCH_NAME>';
        echo '<ADDRESS>'.htmlentities($row["ADDRESS"], ENT_QUOTES).'</ADDRESS>';
        echo '<AREA_CODE_Main>'.$row["AREA_CODE_Main"].'</AREA_CODE_Main>';
        echo '<TELEPHONE_Main>'.$row["TELEPHONE_Main"].'</TELEPHONE_Main>';
        echo '<Mobile_Area_M>'.$row["Mobile_Area_M"].'</Mobile_Area_M>';
        echo '<MOBILE_M>'.$row["MOBILE_M"].'</MOBILE_M>';
        echo '<ANTH_TELEPHONE_AREACODE>'.$row["ANTH_TELEPHONE_AREACODE"].'</ANTH_TELEPHONE_AREACODE>';
        echo '<ANTH_TELEPHONE_PHONE>'.$row["ANTH_TELEPHONE_PHONE"].'</ANTH_TELEPHONE_PHONE>';
        echo '<FAX_Area_Code>'.$row["FAX_Area_Code"].'</FAX_Area_Code>';
        echo '<FAX_Area_Phone>'.$row["FAX_Area_Phone"].'</FAX_Area_Phone>';
        echo '<email>'.$row["email"].'</email>';
        echo '<URL>'.$row["URL"].'</URL>';
        echo '</Listings>';
}

While($row = mysql_fetch_array($result))
{
      $item_no++;
      if ($item_no < $start) { continue; }
      $line_no++;
      if ($line_no > $max_lines) { break; }
        echo '<Listings>';
        echo '<LISTING_ID>'.$row["LISTING_ID"].'</LISTING_ID>';
        echo '<BRANCH_NAME>'.htmlentities($row["BRANCH_NAME"], ENT_QUOTES).'</BRANCH_NAME>';
        echo '<ADDRESS>'.htmlentities($row["ADDRESS"], ENT_QUOTES).'</ADDRESS>';
        echo '<AREA_CODE_Main>'.$row["AREA_CODE_Main"].'</AREA_CODE_Main>';
        echo '<TELEPHONE_Main>'.$row["TELEPHONE_Main"].'</TELEPHONE_Main>';
        echo '<Mobile_Area_M>'.$row["Mobile_Area_M"].'</Mobile_Area_M>';
        echo '<MOBILE_M>'.$row["MOBILE_M"].'</MOBILE_M>';
        echo '<ANTH_TELEPHONE_AREACODE>'.$row["ANTH_TELEPHONE_AREACODE"].'</ANTH_TELEPHONE_AREACODE>';
        echo '<ANTH_TELEPHONE_PHONE>'.$row["ANTH_TELEPHONE_PHONE"].'</ANTH_TELEPHONE_PHONE>';
        echo '<FAX_Area_Code>'.$row["FAX_Area_Code"].'</FAX_Area_Code>';
        echo '<FAX_Area_Phone>'.$row["FAX_Area_Phone"].'</FAX_Area_Phone>';
        echo '<email>'.$row["email"].'</email>';
        echo '<URL>'.$row["URL"].'</URL>';
        echo '</Listings>';
}
echo '</Branches>';
?>
0
 
LVL 17

Expert Comment

by:OmniUnlimited
Comment Utility
Oh, I think I might have misunderstood the question.  Are you saying that you don't want true pagination (like you could see on the merchant items below the main photo at http://sleepamazing.com/?page_id=3&category=22), but simply want headers that state "PAGE 1", "PAGE 2", etc. over the different sections?
0
 
LVL 2

Author Comment

by:rolandmy
Comment Utility
I want true pagination just like you put it. It doesn't show in the website though...

I have include my connection.php and grepv2.php in this posting.

grepv2.php
connection.php
0
 
LVL 17

Expert Comment

by:OmniUnlimited
Comment Utility
Wow, thanks for that, that was very helpful, BUT I sincerly hope that the connection information that you supplied for your database is dummy information, or that you will change this before you put it live.

I think I see what is going on.  The screenshot you supplied is simply a webpage that is interpreting the XML data that is being constructed in your grepv2.php file.  My code is set up to display code on the current page.  We will need to set up a way to transfer the pagination information to the page that is interpreting the XML data.

Would you be so kind as to post the code for that page?
0
 
LVL 2

Author Comment

by:rolandmy
Comment Utility
A lot of those are dummy information. Anyway, I believe you are looking for this code as below?

<?php
// begin the session
session_start();


ini_set('display_errors', 1);

include("../connection.php");

function value_in($element_name, $xml, $content_only = true) {
    if ($xml == false) {
        return false;
    }
    $found = preg_match('#<'.$element_name.'(?:\s+[^>]+)?>(.*?)'.
            '</'.$element_name.'>#s', $xml, $matches);
    if ($found != false) {
        if ($content_only) {
            return $matches[1];  //ignore the enclosing tags
        } else {
            return $matches[0];  //return the full pattern match
        }
    }
    // No match found: return false.
    return false;
}

function element_set($element_name, $xml, $content_only = false) {
    if ($xml == false) {
        return false;
    }
    $found = preg_match_all('#<'.$element_name.'(?:\s+[^>]+)?>' .
            '(.*?)</'.$element_name.'>#s',
            $xml, $matches, PREG_PATTERN_ORDER);
    if ($found != false) {
        if ($content_only) {
            return $matches[1];  //ignore the enlosing tags
        } else {
            return $matches[0];  //return the full pattern match
        }
    }
    // No match found: return false.
    return false;
}

function element_attributes($element_name, $xml) {
    if ($xml == false) {
        return false;
    }
    // Grab the string of attributes inside an element tag.
    $found = preg_match('#<'.$element_name.
            '\s+([^>]+(?:"|\'))\s?/?>#',
            $xml, $matches);
    if ($found == 1) {
        $attribute_array = array();
        $attribute_string = $matches[1];
        // Match attribute-name attribute-value pairs.
        $found = preg_match_all(
                '#([^\s=]+)\s*=\s*(\'[^<\']*\'|"[^<"]*")#',
                $attribute_string, $matches, PREG_SET_ORDER);
        if ($found != 0) {
            // Create an associative array that matches attribute
            // names to attribute values.
            foreach ($matches as $attribute) {
                $attribute_array[$attribute[1]] = $attribute[2];
            }
            return $attribute_array;
        }
    }
    // Attributes either weren't found, or couldn't be extracted
    // by the regular expression.
    return false;
}

//$id = $_GET["Id"];
$what = $_GET["What"];
$where = $_GET["Where"];
/*$pageno = $_GET["PageNumber"];
$resultsperpage = $_GET["ResultsPerPage"];*/
$pageno = 1;
$resultsperpage = 1;

if(strtolower($where) == 'oregon' || strtolower($where) == 'oklahoma' || strtolower($where) == 'hawaii')
{
   $searchterm = 'searchprovince';
}
else
{
   $searchterm = 'searchcity';
}

if(strtolower($where) == 'all')
  $where = "";  

$what = urlencode($what);
$where = urlencode($where);

$am_url = "http://website.com/search/?sei=SPHSystem&query=<AMQuery%20xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'%20xsi:noNamespaceSchemaLocation=''><MainQuery><Field%20name='what'><Term%20type='exact'>$what</Term></Field><Field%20name='$searchterm'><Term%20type='exact'>$where</Term></Field><StructuredItems></StructuredItems><Sort><SortBy%20fieldName='enspl'%20/><SortBy%20fieldName='category'%20/><SortBy%20fieldName='totalpoints'%20/><SortBy%20fieldName='AMRelevancy'%20/><SortBy%20fieldName='endisplay'%20value='EqualTo1'%20/></Sort><IsFirstLanguageQuery>no</IsFirstLanguageQuery></MainQuery><Presentation><PageNumber>$pageno</PageNumber><ResultsPerPage>$resultsperpage</ResultsPerPage></Presentation></AMQuery>";

$xml = "";
  $f = fopen( $am_url, 'r' );
  while( $data = fread( $f, 4096 ) ) {
  $xml .= $data;  
  }
  fclose( $f );

$attribute_array = element_attributes('Listings', $xml);
$returnedResultsNum = $attribute_array['returnedResultsNum'];      //total result per page
$returnedResultsNum = preg_replace('/"/','',$returnedResultsNum);
$totalResultsNum = $attribute_array['totalResultsNum'];      //total listing
$totalResultsNum = preg_replace('/"/','',$totalResultsNum);

//echo "total listing: ".$totalResultsNum."<br/>";

//get all listings and filter listing with geocode
$am_url2 = "http://website.com/search/?sei=SPHSystem&query=<AMQuery%20xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'%20xsi:noNamespaceSchemaLocation=''><MainQuery><Field%20name='what'><Term%20type='exact'>$what</Term></Field><Field%20name='$searchterm'><Term%20type='exact'>$where</Term></Field><StructuredItems></StructuredItems><Sort><SortBy%20fieldName='enspl'%20/><SortBy%20fieldName='category'%20/><SortBy%20fieldName='totalpoints'%20/><SortBy%20fieldName='AMRelevancy'%20/><SortBy%20fieldName='endisplay'%20value='EqualTo1'%20/></Sort><IsFirstLanguageQuery>no</IsFirstLanguageQuery></MainQuery><Presentation><PageNumber>1</PageNumber><ResultsPerPage>$totalResultsNum</ResultsPerPage></Presentation></AMQuery>";

$xml2 = "";
  $f2 = fopen( $am_url2, 'r' );
  while( $data2 = fread( $f2, 4096 ) ) {
  $xml2 .= $data2;  
  }
  fclose( $f2 );

$attribute_array2 = element_attributes('Listings', $xml2);
$returnedResultsNum2 = $attribute_array['returnedResultsNum'];      //total listing
$totalResultsNum2 = $attribute_array['totalResultsNum'];      //total result per page

$resultdisplay = preg_replace('/"/','',$returnedResultsNum2);
$splitlisting = element_set("ListRes", $xml2);

$item_set = element_set('Result', $xml2);

$listingno = 0;      //get total listing with geocode
$branchno = 0;      //get total listing(geocode) with branches

if (isset($_SESSION["arruniquecat"]) && $_SESSION["arruniquecat"] == $what) {
      //echo "Same category: ".$_SESSION["arruniquecat"][0]."<br/>";
      include("getlistingbranch-inc.php");      
}else{
      session_destroy();
      $arrwhat[] = $what;
      $_SESSION["arruniquecat"] = $arrwhat;
      //echo "Different category: ".$_SESSION["arruniquecat"][0]."<br/>";
      //echo "get: ".$what.", session: ".$_SESSION["arruniquecat"][0]."<br/>";      
      include("getlistingbranch-inc.php");
}


//session_destroy();


echo "<MetaData>";
$splitmetadata = element_set("MetaData", $xml, 1);
print_r($splitmetadata[0]);
echo "</MetaData>";

$load = microtime();
echo "<LoadingTime>Load Time ".number_format($load,2)." seconds</LoadingTime>";

echo "</AMResult>";
echo "</AMResults>";
?>
0
 
LVL 17

Expert Comment

by:OmniUnlimited
Comment Utility
Thanks, but the output from that code does not match your screenshot.  Is the screenshot just meant to be an example?  Can you give me a screenshot of what it actually looks like instead?
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 2

Author Comment

by:rolandmy
Comment Utility
The screenshot was done in MS Word. It's a reference that need to be followed. Also means, I need it to look like the screenshot. The right column of the screenshot.
0
 
LVL 17

Expert Comment

by:OmniUnlimited
Comment Utility
OK, so do you have any output at all?  Is any formatting applied to the output?
0
 
LVL 2

Author Comment

by:rolandmy
Comment Utility
If you combine can combine grepv2.php and the lastest code provided above, it would be ideal.

Let's say the result are 2 HQ with a total of 3 branches between them and 5 results per page. Page 1 would be:

HQ1
HQ2
HQ1 BRANCH1
HQ1 BRANCH2
HQ2 BRANCH1

OR

Let's say the result are 5 HQ with a total of 4 branches between them and 5 results per page. Page 1 would be:

HQ1
HQ2
HQ3
HQ4
HQ5


Page 2 would be:

HQ1 BRANCH1
HQ1 BRANCH2
HQ2 BRANCH1
HQ5 BRANCH1
0
 
LVL 2

Author Comment

by:rolandmy
Comment Utility
Just a normal output with text. No formatting yet, hence I put this problem up in EE.
0
 
LVL 17

Expert Comment

by:OmniUnlimited
Comment Utility
OK, but with the code you are seeing your results display on the screen unformatted, right?

I need to verify the current formatting with the code you gave me.  Can you run a sample HQ for me and when you have the results on the screen, do a right-click and choose "View Source" from the popup menu, then select and copy the full HTML output and post it here?  I'd really appreciate it.
0
 
LVL 2

Author Comment

by:rolandmy
Comment Utility
From the code, result is:

<?xml version="1.0" encoding="UTF-8"  standalone="no" ?><AMResults><AMResult><Listings returnedResultsNum="2" totalResultsNum="2"><ListRes index="0" relevanceScore="0"><Result><listingid>12345</listingid><enbusname>HQ1</enbusname><mainarea>03</mainarea><mainnumber>27805701</mainnumber><maindisplay>555-5325</maindisplay><localzip>N13 5DT</localzip><encivicno>098765</encivicno><enstreet>Address1</enstreet><ensuffix>Address2</ensuffix><encity>City1</encity><enprov>Province1</enprov><enzip>23456</enzip><lat>3.131764418</lat><long>101.6840017</long><totalpoints>4289</totalpoints><localurl>http://www.website.com/</localurl><enurl>http://www.website.com/</enurl><localclick2call>0327805701</localclick2call><enclick2call>5555325</enclick2call><amrawlocation>0445100143781298xml_b8761950.0</amrawlocation><localhasinfo>0</localhasinfo><enhasinfo>1</enhasinfo><enlogo>xxx/38635/38635.jpg</enlogo><enlogo>xxx/38635/38635.jpg</enlogo><enlogo>xxx/38635/38635.jpg</enlogo><category>1089001</category></Result><RankVals><Val name="enspl"></Val><Val name="category"></Val><Val name="totalpoints"></Val><Val name="endisplay"></Val></RankVals><MatchedObjs><MatchedObj><Obj name="AMClientInfo"></Obj></MatchedObj></MatchedObjs></ListRes><ListRes index="1" relevanceScore="0"><Result><listingid>281450</listingid><enbusname>HQ2</enbusname><mainarea>03</mainarea><mainnumber>79832280</mainnumber><maindisplay>03-79832280</maindisplay><localzip>58100</localzip><encivicno>501448</encivicno><enstreet>No 15-A, Jalan Bukit Desa 5</enstreet><ensuffix>Taman Bukit Desa, Off Jalan Klang Lama</ensuffix><encity>Wilayah Persekutuan</encity><enprov>Kuala Lumpur</enprov><enzip>58100</enzip><lat>3.21462</lat><long>101.61934</long><totalpoints>165</totalpoints><localurl></localurl><enurl></enurl><localclick2call>0379832280</localclick2call><enclick2call>0379832280</enclick2call><amrawlocation>0221200102265718xml_b8761950.0</amrawlocation><localhasinfo>1</localhasinfo><enhasinfo>1</enhasinfo><enlogo>Production/51927/51927.jpg</enlogo><enlogo>Production/51927/51927.jpg</enlogo><enlogo>Production/51927/51927.jpg</enlogo><category>1089001</category></Result><RankVals><Val name="enspl"></Val><Val name="category"></Val><Val name="totalpoints"></Val><Val name="endisplay"></Val></RankVals><MatchedObjs><MatchedObj><Obj name="AMClientInfo"></Obj></MatchedObj></MatchedObjs></ListRes></Listings><MetaData><MDGroup numOfObjects="1" objectName="enprov"><MDObj value="Kuala Lumpur"><Info name="totalcount" type="counter">2</Info><Info name="counter2" type="type2">4</Info><Info name="counter3" type="type3">0</Info><Info name="counter4" type="type4">0</Info><Info name="counter5" type="type5">100</Info><Info name="counter6" type="type6">0</Info></MDObj></MDGroup><MDGroup numOfObjects="1" objectName="enpaymeth"><MDObj value="Cash, Cheque, Bank Transfer"><Info name="totalcount" type="counter">1</Info><Info name="counter2" type="type2">4</Info><Info name="counter3" type="type3">0</Info><Info name="counter4" type="type4">0</Info><Info name="counter5" type="type5">100</Info><Info name="counter6" type="type6">0</Info></MDObj></MDGroup><MDGroup numOfObjects="1" objectName="category"><MDObj value="1089001"><Info name="totalcount" type="counter">2</Info><Info name="counter2" type="type2">4</Info><Info name="counter3" type="type3">0</Info><Info name="counter4" type="type4">0</Info><Info name="counter5" type="type5">0</Info><Info name="counter6" type="type6">0</Info></MDObj></MDGroup></MetaData><LoadingTime>Load Time 0.60 seconds</LoadingTime></AMResult></AMResults>


As for the grepv2.php, result is:

<?xml version="1.0" encoding="UTF-8"  standalone="no" ?><Branches><Listings><LISTING_ID>108756</LISTING_ID><BRANCH_NAME>Holiday Villa Hotels &amp; Resorts</BRANCH_NAME><ADDRESS>B-16-8, Megan Avenue II, No. 12, Jln Yap Kwan Seng, 50744, Kuala Lumpur, Wilayah Persekutuan</ADDRESS><AREA_CODE_Main>03</AREA_CODE_Main><TELEPHONE_Main>21622922</TELEPHONE_Main><Mobile_Area_M></Mobile_Area_M><MOBILE_M></MOBILE_M><ANTH_TELEPHONE_AREACODE></ANTH_TELEPHONE_AREACODE><ANTH_TELEPHONE_PHONE></ANTH_TELEPHONE_PHONE><FAX_Area_Code>03</FAX_Area_Code><FAX_Area_Phone>21622937</FAX_Area_Phone><LONGTITUDE>101.711770</LONGTITUDE><LATITUDE>3.162415</LATITUDE><email>centralresv@holidayvilla.com.my</email><URL></URL></Listings></Branches>
0
 
LVL 17

Expert Comment

by:OmniUnlimited
Comment Utility
OK, I see a problem.  Both of these are XML packets.  You can't do any formatting in XML packets, they only provide information.  I can include pagination info in the XML, but there is no way to format it for the screen except through use of an XML parser.
0
 
LVL 17

Expert Comment

by:OmniUnlimited
Comment Utility
Why have you set up the information to be extracted as XML anyway?  Are you planning to transmit the information somewhere?
0
 
LVL 2

Author Comment

by:rolandmy
Comment Utility
Yes, information is meant to be transmitted somewhere.

XML parser? Sorry am kinda blind when it comes to XML. Any chance of including a XML parser that will show the result as intended in my first posting here (right column of image).
0
 
LVL 17

Expert Comment

by:OmniUnlimited
Comment Utility
Sure, I can create a simple XML parser with formatting.  What you will need to do is remove all my coding from your files, because pagination will occur inside the parser, not in the XML creation.

Now, I need to know just how much of this I need to do for you.  Do you know HTML and CSS so that if I give you just a raw, unformatted layout you could add styling so that it displays the way you want, or do I need to lay this out in its finished form?
0
 
LVL 17

Expert Comment

by:OmniUnlimited
Comment Utility
OK, I just did some preliminary testing on the XML parser.  It looks like the xml packets you gave me were only for 1 item each.  I need an XML sample of at least two, preferably more than five items so that I can do a test on the pagination.
0
 
LVL 2

Author Comment

by:rolandmy
Comment Utility
From the code, the results I have saved in list.xml while from grepv2.php, the result I have saved in grepv2-list.xml


list.xml
grepv2-result.xml
0
 
LVL 2

Author Comment

by:rolandmy
Comment Utility
Oh, didn't noticed the other question. Lay it out in its finished form please.
0
 
LVL 17

Accepted Solution

by:
OmniUnlimited earned 500 total points
Comment Utility
OK, well I have finished the coding for your two XML parsers.  You need to know that list.xml has a malformed XML where your tag looks like <RankVals>Val instead of <RankVals><Val which caused a parse error.  Also you need to remember that if you are going to transmit in XML, all the data must be in UTF-8 format.  You had an apostophe that appeared to come from a word processor like Microsoft Word, so I had to change that out as well.

I understand you want to see this in the finished form, but laying out CSS is easy.  My most important goal in posting this response was to give you code that would display the information you are transmitting in a paginated format like you requested.  We can work on the layout later.

Since these two XML files format differently, I had to make two separate parsers.  The first parser to parse out the list.xml file goes like this:
 
<?php
echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
echo '<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">';
echo '<head profile="http://gmpg.org/xfn/11">';
echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
echo '<title>XML Parser - Test 1</title>';
echo '</head>';
echo '<body>';
$xml = simplexml_load_file('http://test.lcwdcv.com/wp-content/themes/default/xml1.php'); // Change to the url of your XML file
$json = json_encode($xml);
$array = json_decode($json,TRUE);
$url = "http://test.lcwdcv.com/ee/test2/?status=test";  // Change also to the page you are displaying
$max_lines = 5;
$total_rec = count($array['AMResult']['Listings']['ListRes']);
$pages = ceil($total_rec / $max_lines);
$item_no = 0;
$line_no = 0;
if(isset($_GET['page_number'])) {	
	$curpage = $_GET['page_number'];
} else {
	$curpage = 1;
}
$start = (($curpage - 1) * $max_lines) + 1;
if ($pages > 1) {
	$end = $start + $max_lines - 1;
	if ($end > $total_rec) { $end = $total_rec; }
	echo "<div class='tablenav-pages'>";
	echo "<span class='displaying-num'>";
	echo "Displaying " . $start . "-" . $end . " of " . $total_rec;
	echo "</span>";
	echo show_pages($pages, $url, $curpage, false);
	echo "</div>";
}
if ($total_rec > 0) {
	foreach($array['AMResult']['Listings']['ListRes'] as $key => $value) {
		$item_no++;
		if ($item_no < $start) { continue; }
		$line_no++;
		if ($line_no > $max_lines) { break; }
		echo "<br />";
		if (is_array($value))
			get_values($value);
		else
			echo $key . ": " . $value . "<br />";
	}
} else {
	echo "No records available for display.";
}
echo '</body>';
echo '</html>';

function get_values($array) {
	foreach($array as $key => $value) {
		if (is_array($value))
			get_values($value);
		else
			echo $key . ": " . $value . "<br />";
	}
}

function show_pages($pages, $link_url, $curpage, $show_word=true) {
    // shows page numbers
    $output = "<div class='page_numbers'>\n\r";
    $output .= "<span class='flatview'>\n\r";
	if ($curpage > 1) {
	  	$prev = $curpage - 1;
	    $output .= "<a href='".$link_url."&page_number=$prev' >&laquo;";
		if ($show_word) { $output .= " Prev"; }
		$output .= "</a>\n\r";
	}
    for($i=1;$i<=$pages;++$i) {
      if ($curpage == $i) {
        if($_GET['view_all'] != 'true') {
          $selected = "class='selected'";
		} else {
    	  $selected = "class='notselected'";
	  	}
	  } else {
         $selected = "class='notselected'";
	  }
	  if ($i > 1) {
		 if ($pages > 13) {
				if ($curpage > 7) {
					if ($i == 3) {
						$output .= '...&nbsp;';
						continue;
					}
					if ($curpage < $pages - 7) {
						if ($i < 3) {
							$output .= "  <a href='".$link_url."&page_number=$i' $selected >$i</a>\n\r";
							continue;
						}
						if ($i < $curpage - 3) {
							continue;
						}
						if (($i > $curpage + 3) && ($i < $pages - 2)) { 
							continue; 
						}
						if ($i == $pages - 2) {
							$output .= '...&nbsp;';
							continue;
						}
					} else {
						if ($i < 3) {
							$output .= "  <a href='".$link_url."&page_number=$i' $selected >$i</a>\n\r";
							continue;
						}
						if ($i < $pages - 9) {
							continue;
						}
					}
				} else {
					if (($i > 10) && ($i < $pages - 2)) { 
						continue; 
					}
					if ($i == $pages - 2) {
						$output .= '...&nbsp;';
						continue;
					}
				}
			}
		}
      $output .= "  <a href='".$link_url."&page_number=$i' $selected >$i</a>\n\r";
	}    
	if ($curpage < $pages) {
	  	$next = $curpage + 1;
	    $output .= "<a href='".$link_url."&page_number=$next' >";
		if ($show_word) { $output .= "Next "; }
		$output .= "&raquo;</a>\n\r";
	}
    $output .= "</span>\n\r";
    $output .= "</div>\n\r";
	return $output;
}
?>

Open in new window


The second one, set up to parse grepv2-result.xml goes like this:
 
<?php
echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
echo '<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">';
echo '<head profile="http://gmpg.org/xfn/11">';
echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
echo '<title>XML Parser - Test 2</title>';
echo '</head>';
echo '<body>';
$xml = simplexml_load_file('http://test.lcwdcv.com/wp-content/themes/default/xml2.php'); // Change to the url of your XML file
$json = json_encode($xml);
$array = json_decode($json,TRUE);
$url = "http://test.lcwdcv.com/ee/test2/?status=test"; // Change also to the page you are displaying
$max_lines = 5;
$total_rec = count($array['Listings']);
$pages = ceil($total_rec / $max_lines);
$item_no = 0;
$line_no = 0;
if(isset($_GET['page_number'])) {	
	$curpage = $_GET['page_number'];
} else {
	$curpage = 1;
}
$start = (($curpage - 1) * $max_lines) + 1;
if ($pages > 1) {
	$end = $start + $max_lines - 1;
	if ($end > $total_rec) { $end = $total_rec; }
	echo "<div class='tablenav-pages'>";
	echo "<span class='displaying-num'>";
	echo "Displaying " . $start . "-" . $end . " of " . $total_rec;
	echo "</span>";
	echo show_pages($pages, $url, $curpage, false);
	echo "</div>";
}
if ($total_rec > 0) {
	foreach($array['Listings'] as $key => $value) {
		$item_no++;
		if ($item_no < $start) { continue; }
		$line_no++;
		if ($line_no > $max_lines) { break; }
		echo "<br />";
		if (is_array($value))
			get_values($value);
		else
			echo $key . ": " . $value . "<br />";
	}
} else {
	echo "No records available for display.";
}
echo '</body>';
echo '</html>';

function get_values($array) {
	foreach($array as $key => $value) {
		if (is_array($value))
			get_values($value);
		else
			echo $key . ": " . $value . "<br />";
	}
}

function show_pages($pages, $link_url, $curpage, $show_word=true) {
    // shows page numbers
    $output = "<div class='page_numbers'>\n\r";
    $output .= "<span class='flatview'>\n\r";
	if ($curpage > 1) {
	  	$prev = $curpage - 1;
	    $output .= "<a href='".$link_url."&page_number=$prev' >&laquo;";
		if ($show_word) { $output .= " Prev"; }
		$output .= "</a>\n\r";
	}
    for($i=1;$i<=$pages;++$i) {
      if ($curpage == $i) {
        if($_GET['view_all'] != 'true') {
          $selected = "class='selected'";
		} else {
    	  $selected = "class='notselected'";
	  	}
	  } else {
         $selected = "class='notselected'";
	  }
	  if ($i > 1) {
		 if ($pages > 13) {
				if ($curpage > 7) {
					if ($i == 3) {
						$output .= '...&nbsp;';
						continue;
					}
					if ($curpage < $pages - 7) {
						if ($i < 3) {
							$output .= "  <a href='".$link_url."&page_number=$i' $selected >$i</a>\n\r";
							continue;
						}
						if ($i < $curpage - 3) {
							continue;
						}
						if (($i > $curpage + 3) && ($i < $pages - 2)) { 
							continue; 
						}
						if ($i == $pages - 2) {
							$output .= '...&nbsp;';
							continue;
						}
					} else {
						if ($i < 3) {
							$output .= "  <a href='".$link_url."&page_number=$i' $selected >$i</a>\n\r";
							continue;
						}
						if ($i < $pages - 9) {
							continue;
						}
					}
				} else {
					if (($i > 10) && ($i < $pages - 2)) { 
						continue; 
					}
					if ($i == $pages - 2) {
						$output .= '...&nbsp;';
						continue;
					}
				}
			}
		}
      $output .= "  <a href='".$link_url."&page_number=$i' $selected >$i</a>\n\r";
	}    
	if ($curpage < $pages) {
	  	$next = $curpage + 1;
	    $output .= "<a href='".$link_url."&page_number=$next' >";
		if ($show_word) { $output .= "Next "; }
		$output .= "&raquo;</a>\n\r";
	}
    $output .= "</span>\n\r";
    $output .= "</div>\n\r";
	return $output;
}
?>

Open in new window


You can see these in action at the following locations:

list.xml parser: http://test.lowcostwebdesignchulavista.com/ee/test1/

grepv2-result.xml parser: http://test.lowcostwebdesignchulavista.com/ee/test2/
0
 
LVL 2

Author Comment

by:rolandmy
Comment Utility
No time to test yet. Switched to another project. Anyway, will accept solution. Looks logical. Will also reply here in a week after I test.

Thanks for the help thus far. Appreciated it.
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

763 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

6 Experts available now in Live!

Get 1:1 Help Now