Reader.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. /**
  3. * Utility class to access OpenDocument spreadsheets read-only
  4. *
  5. * Requires PHP 5.3
  6. *
  7. * @license CeCILL 2.0
  8. * @copyright 2005-2012 Ouest Systemes Informatiques
  9. */
  10. declare(strict_types=1);
  11. namespace Osinet\OpenDocument\Calc;
  12. /**
  13. * Utility class to access OpenDocument spreadsheets read-only
  14. */
  15. class Reader {
  16. const NS_TABLE = "urn:oasis:names:tc:opendocument:xmlns:table:1.0";
  17. const NS_OFFICE = "urn:oasis:names:tc:opendocument:xmlns:office:1.0";
  18. /**
  19. * @var \DOMDocument $xml
  20. */
  21. public $xml;
  22. /**
  23. * @var \DOMXPath $xpath
  24. */
  25. public $xpath;
  26. function __construct(string $path) {
  27. $this->xml = new \DOMDocument();
  28. $this->xml->preserveWhiteSpace = FALSE;
  29. $this->xml->load($path);
  30. $this->xpath = new \DOMXPath($this->xml);
  31. $this->xpath->registerNameSpace('office', self::NS_OFFICE);
  32. $this->xpath->registerNameSpace('table', self::NS_TABLE);
  33. }
  34. /**
  35. * Return a DOMNodeList of the worksheets available in the document
  36. *
  37. * @return \DOMNodeList<\DOMNode>
  38. */
  39. function getCalcSheets(): \DOMNodeList {
  40. $sq = '//table:table';
  41. $list = $this->xpath->query($sq);
  42. unset($sq);
  43. if ($list === FALSE) {
  44. $list = new \DOMNodeList();
  45. }
  46. return $list;
  47. }
  48. /**
  49. * Return the names of the worksheets available in the document
  50. *
  51. * @return array<string>
  52. */
  53. function getCalcSheetNames() {
  54. $dnlSheets = $this->getCalcSheets();
  55. $ret = array();
  56. foreach ($dnlSheets as $node) {
  57. $ret[] = $node->getAttributeNS(self::NS_TABLE, 'name');
  58. }
  59. unset($dnlSheets);
  60. return $ret;
  61. }
  62. /**
  63. * Return the rows in the spreadsheet as a DOMNodeList.
  64. *
  65. * WARNING: this means ALL the rows, in all the sheets, not just the first sheet
  66. *
  67. * @param string $namedRange
  68. * Optional name of range, notably Sheet name
  69. * @return \DOMNodeList<\DOMNode>
  70. */
  71. function getRows ($namedRange = NULL): \DOMNodeList {
  72. $query = empty($namedRange)
  73. ? '//table:table-row'
  74. : '//table:table[@table:name="' . $namedRange . '"]/table:table-row';
  75. $list = $this->xpath->query($query);
  76. unset($query);
  77. if ($list === FALSE) {
  78. $list = new \DOMNodeList();
  79. }
  80. return $list;
  81. }
  82. }