0

I am trying to parse some basic html using xpath and running into issues. The returned output is always empty using what I am reading the xpath docs to say works. Below is my first attempt at making this work. Any help is appreciated as always guys and gals.

$html  = '<ul>';
$html .= '  <li id="stuff-12345"> some content here </li>';
$html .= '  <li id="stuff-54321"> some other content here </li>';
$html .= '</ul>';

    $dom = new DOMDocument(); 
    $dom->loadHTML($html);  
    $xpath = new DOMXPath($dom); 
    $result = $xpath->query('//ul/li'); 
    foreach($result as $e){
        echo $e->item(0)->nodeValue . "\n";
    }
Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
Jaime Cross
  • 523
  • 1
  • 3
  • 15

1 Answers1

1

DOMXPath::query returns a DOMNodeList. When you are doing

foreach($result as $e){

you are iterating over the DOMElement items a DOMNodeList. DOMElement does not have an item() method. Only DOMNodeList has that. Try with

foreach($result as $e){
    echo $e->nodeValue, PHP_EOL;
}
Gordon
  • 312,688
  • 75
  • 539
  • 559
  • Thanks Gordon, that worked perfectly. Do you happen to know how I could refine the xpath query to only get li's with id="stuff-###" ? I could not seem to find anything in the docs where a wildcard could be used. – Jaime Cross Mar 09 '11 at 17:28
  • 2
    @Jaime `//ul/li[@id="stuff-12345"]` to get that exact ID. `//ul/li[starts-with(@id, "stuff")]` to get li elements having an id attribute value starting with 'stuff' and `'//ul/li[contains(@id, "stuff")]'` to get li elements having 'stuff' anywhere in the id attribute – Gordon Mar 09 '11 at 17:39