tags:

views:

987

answers:

2

Can someone explain to me what is nodeValue in this and write out how nodeValue look like or write out what's in nodeValue? EDIT: Sorry! Yes, this is PHP.

And..

foreach ($elements as $e) {
  echo $e->nodeValue;
}

What does the arrow thingy mean (->)? That's an array right? Well if you can explain to me this one part that would be great...

Here's the source:

$html = file_get_contents('http://website.com/');

$dom = new DOMDocument();

@$dom->loadHTML($html);

$xPath = new DOMXPath($dom);


$elements = $xPath->query("//*[@id='announcement']");


foreach ($elements as $e) {
  echo $e->nodeValue;
}

Update: I thought I'll write out the question here instead of leaving it in comments. Let's say I had 5 node values found and what if I just wanted to echo the 2nd node value? How would I do that? echo $e->nodeValue2;?

A: 

That looks suspiciously like PHP. I believe that it is getting the contents of the web page from http://website.com, loading it into a DOM Document (Document Object Model), and then performing an XPath query on it which looks for all the nodes which have an 'id' attribute that have a value of 'announcement', and then for each of those nodes, echoing the value.

The node value would be: <node>This is the node value</node>

-> is how you access a class member like a method or property in PHP.

sgrassie
Oh, I see. I understood everything until the last two sentences.So let's say I had 5 node values found. How would it look like when it's looped out one by one? I need to see the visual result. Also, What if I just wanted to echo the 2nd node value? How would I do that?
Doug
Don't know about PHP, but generally in DOM nodeValue of Elements is null. And //*[@id="announcement"] should return Elements. And usually there's a single element with the given ID. See https://developer.mozilla.org/En/NodeValue and http://www.w3.org/TR/xpath#path-abbrev
Nickolay
@Nickolay the mozilla page you linked to says: "For the document itself, nodeValue returns null. For text, comment, and CDATA nodes, nodeValue returns the content of the node. For attribute nodes, the value of the attribute is returned." So in @Doug's case, nodeValue should return the text content of the elements found by the XPath query. As far as I know, the ID doesn't have to be unique.
sgrassie
A: 
echo $e->items[1]->nodeValue

Arrays in PHP start at 0, so the element at position 1 is the second value in the array.

sgrassie
The arrow really confuses things for me. If I used this small piece of code in my script, it wouldn't do anything because the array would have to be set as items before I can actually do that right? Just making sure I understand everything.
Doug