1. <?php
  2. /**
  3. * Compares two datasets of DOM elements and outputs the differences.
  4. *
  5. * @param mixed $dataset1 The first dataset of DOM elements (array of DOMNode objects).
  6. * @param mixed $dataset2 The second dataset of DOM elements (array of DOMNode objects).
  7. * @return void Outputs the differences to the console.
  8. */
  9. function diffDomDatasets($dataset1, $dataset2) {
  10. if (!is_array($dataset1) || !is_array($dataset2)) {
  11. echo "Error: Datasets must be arrays.\n";
  12. return;
  13. }
  14. $len1 = count($dataset1);
  15. $len2 = count($dataset2);
  16. $maxLength = max($len1, $len2);
  17. for ($i = 0; $i < $maxLength; $i++) {
  18. if ($i >= $len1) {
  19. echo "Dataset 1 has fewer elements, adding elements from Dataset 2.\n";
  20. printDomElement($dataset2[$i]); // Output element from dataset 2
  21. } elseif ($i >= $len2) {
  22. echo "Dataset 2 has fewer elements.\n";
  23. printDomElement($dataset1[$i]); // Output element from dataset 1
  24. } else {
  25. if ($dataset1[$i] !== $dataset2[$i]) {
  26. echo "Difference at index $i:\n";
  27. printDomElement($dataset1[$i]);
  28. printDomElement($dataset2[$i]);
  29. }
  30. }
  31. }
  32. }
  33. /**
  34. * Prints a DOM element to the console (basic representation).
  35. * @param DOMNode $node The DOMNode to print.
  36. */
  37. function printDomElement(DOMNode $node) {
  38. echo " Type: " . get_class($node) . "\n";
  39. echo " Tag: " . $node->nodeName . "\n";
  40. echo " Attributes: ";
  41. foreach ($node->attributes as $attr) {
  42. echo $attr->name . "=\"" . $attr->value . "\" ";
  43. }
  44. echo "\n";
  45. }
  46. //Example Usage (for testing)
  47. /*
  48. $doc1 = new DOMDocument();
  49. $element1 = $doc1->createElement('div');
  50. $element1->setAttribute('id', 'test1');
  51. $element1->appendChild($doc1->createElement('p', 'First Element'));
  52. $doc1->appendChild($element1);
  53. $element2 = $doc1->createElement('div');
  54. $element2->setAttribute('id', 'test1');
  55. $element2->appendChild($doc1->createElement('p', 'Second Element'));
  56. $doc1->appendChild($element2);
  57. $dataset1 = [$doc1->getElementById('test1')];
  58. $dataset2 = [$doc1->getElementById('test1')];
  59. diffDomDatasets($dataset1, $dataset2);
  60. */
  61. ?>

Add your comment