views:

110

answers:

1

So I wanted to know if there was a way to grab a specific HTML tag's information using PHP.

Let's say we had this code:

<ul>
<li>First List</li>
<li>Second List</li>
<li>Third List</li>
</ul>

How could I search the HTML and pull the third list item's value into a variable? Or is there a way you could pull the entire unordered list into an array?

+3  A: 

Has not been tested or compiled, but one way is create a function that utilizes PHP: DOMDocument and its method getElementsByTagName which returns a PHP: DOMNodeList that you can access the node at a specific index.

function grabAttributes($file, $tag, $index) {
 $dom = new DOMDocument();
 if (!@$dom->load($file)) {
   echo $file . " doesn't exist!\n";
   return;
 }

 $list = $dom->getElementsByTagName($tag); // returns DOMNodeList of given tag
 $newElement = $list->item($index)->nodeValue; // initialize variable 
 return $newElement;
}

If you call grabAttributes("myfile.html", "li", 2) the variable will be set to "Third List"

Or you can make a function to put all the attributes of a given tag into an array.

function putAttributes($file, $tag) {
$dom = new DOMDocument();
if (!@$dom->load($file)) {
  echo $file . " doesn't exist!\n";
  return;
}

$list = $dom->getElementsByTagName($tag); // returns DOMNodeList of given tag
$myArray = array(); // array to contain values.
foreach ($list as $tag) { // loop through node list and add to an array.
    $myArray[] = $tag->nodeValue;
 } 

   return $myArray;
}

If you call putAttributes("myfile.html", "li") it would return array("First List", "Second List", "Third List")

Anthony Forloney
It didn't work. Using grabAttributes I got this error:Catchable fatal error: Object of class DOMElement could not be converted to string in
NessDan
Try `li` instead of `"li"`, also editing the code, I think what I wanted was `$list->item($index)->nodeValue`
Anthony Forloney
You sir, are instant winrar. Thanks for the fixing edit.
NessDan
Not a problem, good luck.
Anthony Forloney