tags:

views:

213

answers:

2

I have a < ul > with some < li >(s). I want to count the number of these < li>s on server side. And if this number qualifies a given condition then i would like to add some more < li> elements to this < ul>. Can someone please help me with this ?

A: 

Use PHP's DOM library, or look up Simple DOM Parser. They both have everything you need for manipulating and searching HTML to the extent of your question

Justin Johnson
Simple DOM Parser worked for me, had to play with it a lil but was fine :)Thank you
Umair
+3  A: 

First a simple example using php's DOM module and XPath

$s = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt;
<html><head><title>...</title></head><body>
  <ul>
    <li>1</li><li>2</li>
  </ul>
  <ul>
    <li>1</li><li>2</li><li>3</li>
  </ul>
  <ul>
    <li>x</li><li>y</li>
  </ul>
</body></html>';

$doc = new DOMDocument;
$doc->loadhtml($s);
$xpath = new DOMXPath($doc);

foreach( $xpath->query('//ul[ count(li)<3 ]') as $ul ) {
  $li = $doc->createElement('li', 'abc...xyz');
  $ul->appendChild($li);
}

echo $doc->savehtml();

and then an oversimplified example of what I meant by "And that function can't include the extra data as well?"

echo firstFunction(array('a'), 'secondFunction');

function firstFunction($arrData, $fnFill=null) {
  $rv = '';
  $counter = 0;
  foreach($arrData as $e) {
    $counter += 1;
    $rv .= '<li>'.htmlspecialchars($e).'</li>';
  }

  if ( 4 > $counter && !is_null($fnFill)) {
    // oh no. Not enough elements. Let's call $fnFill(), it provides some filler material
    $rv .= $fnFill();
  }
  return $rv;
}

// providing extra li elements
function secondFunction() {
  return '<li>x</li><li>y</li><li>z</li>';
}
VolkerK
I think if this solution is tweaked a lil then i can use it, actually I am using two of wordpress plugins, if one plugin returns a count less than required then i use other plugin to fetch the data which returns just li(s) if i can just probably count the number of Li(s) in a ul. and then append an html (which will contain some li elements) at the end of that ul.
Umair