コード例 #1
0
ファイル: dom-node.php プロジェクト: shubo83/php.query
 /**
  * Creates a node.
  *
  * Examples:
  * ```php
  * // creates a simple node with two attributes and inner text
  * $item = new DomNode("item", array("id" => 101, "title" => "Title 101"), "Inner text here...");
  * echo $item;
  *
  * // creates a complex node
  * // in this case we use a callback function to add complex structures into the node
  * $root = new DomNode("root", function ($target) {
  * // adds three subnodes
  *     for ($i = 0; $i < 3; $i++) {
  *         $target->append(
  *              new DomNode("item", array("id" => $i, "title" => "Title $i"), "This is the item $i")
  *         );
  *     }
  *
  *     // appends some XML code
  *     $target->append("<text>This text is added to the end.</text>");
  *
  *     // prepends some XML code
  *     $target->prepend("<text>This text is added to the beginning</text>");
  * });
  * echo $root;
  * ```
  *
  * @param string $nodeName   Node name (not required)
  * @param string $document   Document context (not required)
  * @param array  $attributes List of attributes (not required)
  * @param string $text       Inner text (not required)
  * @param string $callback   Callback function (not required)
  */
 public function __construct($nodeName = null, $document = null, $attributes = null, $text = null, $callback = null)
 {
     $args = ArrHelper::fetch(func_get_args(), array("nodeName" => "string", "document" => "\\DOMDocument", "attributes" => "array", "text" => "scalar", "callback" => "function"));
     // creates a document
     $this->document = $args["document"] === null ? new DOMDocument("1.0", $this->_defaultCharset) : $args["document"];
     $this->document->preserveWhiteSpace = false;
     $this->document->formatOutput = true;
     // creates a DOM element
     if ($args["nodeName"] !== null) {
         $elem = $this->document->createElement($args["nodeName"]);
         $this->document->appendChild($elem);
         array_push($this->elements, $elem);
     }
     // sets attributes
     if ($args["attributes"] !== null) {
         foreach ($args["attributes"] as $name => $value) {
             $this->attr($name, $value);
         }
     }
     // sets inner text
     if ($args["text"] !== null) {
         $this->text($args["text"]);
     }
     // calls callback function
     if ($args["callback"] !== null) {
         $args["callback"]($this);
     }
 }