A modest collection of PHP libraries used at SparkFun.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
1.5 KiB

  1. <?php
  2. namespace SparkLib;
  3. class HTML {
  4. /**
  5. * spit out an HTML tag
  6. *
  7. * takes a tag name, an array of attribute name/values, and an
  8. * optional body.
  9. *
  10. * if an attribute value is a literal true instead of a string,
  11. * just the attribute name will be inserted. this probably isn't
  12. * valid XHTML, but i think it's valid HTML5
  13. *
  14. * @param string tag name
  15. * @param array attribute name/value pairs
  16. * @param string contents of the tag
  17. */
  18. protected function makeTag ($tagname, array $attributes, $contents = null)
  19. {
  20. $close = ($contents === null) ? true : false;
  21. $html = $this->startTag($tagname, $attributes, $close);
  22. // if we got something to put inside, wrap it up
  23. // otherwise put it in a self-closing tag
  24. // n.b., this is potentially flawed for <script>
  25. if ($close)
  26. return $html;
  27. else
  28. return $html . $contents . "</{$tagname}>";
  29. }
  30. /**
  31. * Make a start tag, optionally self-closing.
  32. */
  33. protected function startTag ($tagname, array $attributes = array(), $close = false)
  34. {
  35. // open the tag
  36. $html = '<' . $tagname;
  37. // handle attributes
  38. foreach ($attributes as $a => $v) {
  39. if ($v === null) continue; // nothing
  40. elseif ($v === true) $html .= ' ' . $a; // bare attribute, no value
  41. else $html .= ' ' . $a . '="' . htmlspecialchars($v) . '"'; // attribute="value"
  42. }
  43. if ($close)
  44. return $html . ' />';
  45. else
  46. return $html . '>';
  47. }
  48. }