-7

here is a code:

<?php
$html = <<< HTML
    <div id="one">
<h1>header 1</h1>
<h2>header 2</h2>
<blockquote>
    <p>paragraph1</p>
    <p>paragraph2</p>
</blockquote>
    <b>bold text1</b>
<b>bold text2</b>
</div>
HTML;



$dom = new DOMDocument();
@$dom->loadHTML($html);

/******************3rd part*************/
     echo $dom->childNodes->item(0)->nodeName."<br>";
 echo $dom->childNodes->item(1)->nodeName."<br>";


    /**********1st part**********/
$tags = $dom->getElementsByTagName("blockquote");
foreach($tags as $tag)
{
    $ps=$tag->getElementsByTagName("p");
    foreach($ps as $p)
    {
        echo $p->nodeValue."<br>";
    }
}

/************2nd part**********/
$tags = $dom->getElementById("one");
foreach($tags as $tag)
{
    $hs=$tag->getElementsByTagName("h1");
    foreach($hs as $h)
    {
        echo $h->nodeValue."<br>";
    }
}

?>

Please teach me by example :

  1. What is the firstNode and lastNode in $html? How can I print the text inside those nodes?
  2. Why the second part of the code prints nothing ?
  3. <h2>header 2</h2> is this a single node ?
  4. What is the difference between textContet and nodeValue ?
  5. What is the idea of textContent, item() and childnodes?
  6. How many child odes does div#one contain?
  7. Which are the childNodes of $dom? How can I print their names?
  8. What is the error in the 3rd part of this code? Both lines are showing the same!

I have read @Gordon's answer from here but I need some clear examples.

Community
  • 1
  • 1
Quazi Marufur Rahman
  • 2,603
  • 5
  • 33
  • 51
  • sorry for this type of question . if i violate the rule .. please feel free to delete this post – Quazi Marufur Rahman Aug 30 '11 at 15:40
  • 1
    @qmaruf Try asking one question at a time - you will probably find that some of your questions have previously been asked/answered. – brian_d Aug 30 '11 at 15:45
  • 2
    You're loading an invalid HTML snippet into DOM - it is VERY picky about the structure of what's parsing, and you've suppressed errors with `@` - bad form. – Marc B Aug 30 '11 at 15:45

1 Answers1

1
  1. both are <div id="one"> Note the all the h1, h2 and blockquote nodes are childs of this one.
  2. $dom->getElementById(0); would return the first element. $dom->getElementById(1); would return the second (if it existed) id is the name of an attribute in this tag <div id="one">
  3. Do not understand the question. what do you mean by single node?
  4. textContent: all the texts within the childNodes (http://www.w3schools.com/dom/prop_element_textcontent.asp); nodeValue: value of a node, depending on its type http://www.w3schools.com/dom/prop_document_nodevalue.asp
  5. read on ... this http://www.w3schools.com/htmldom/default.asp

I leave the rest to other SO users.

bpgergo
  • 15,669
  • 5
  • 44
  • 68