Frage

I don't know exactly why, but my span element is a DomText object. And I couldn't get the attribute of the span.

I use the simple DomDocument (instead of xpath) because of this is more faster than other solutions, which I tried.

    $dom = new \DOMDocument();
    $dom->loadHTML($contentOfDom);

    $trs = $dom->getElementsByTagName('tr');

    $result = array();

    $previous = null;
    foreach ($trs as $tr) {
          $current = null;

          foreach ($tr->childNodes as $td) {

                if ($td->nodeName === 'td') {                        
                    $current[] = trim($td->nodeValue);
                    $childOfTD = $td->childNodes->item(0);
                    print_r($childOfTD);
                    //echo 'title:'.$childOfTD->getAttribute('title')."<br>";
                    //var_dump($childOfTD->getAttribute('name') == "title");
                }
         } 
        //.... other codes
}

This is the TD which has a span element:

<td>
    <span class="emphasize" title="this modified">
    2.36
    </span>
</td>       

The $td->nodeValue will get the 2.36 value, this is good. But I don't get the span's title attribute, because I need check that. (However, maybe I can check it before the value will be updated into the database - maybe this is faster)

And this is how look that nodevalue (alias the print_r($element))

 DOMText Object ( 
     [wholeText] => 2.36
     [data] => 2.36
     [length] => 25
     [nodeName] => #text
     [nodeValue] => 2.36
     [nodeType] => 3
     [parentNode] => (object value omitted)
     [childNodes] => 
     [firstChild] => 
     [lastChild] => 
     [previousSibling] =>
     [attributes] =>
     [ownerDocument] => (object value omitted) 
     [namespaceURI] => 
     [prefix] => 
     [localName] => 
     [baseURI] => 
     [textContent] => 2.36
     ) 

Somehow I would like to get the span's title attribute with domdocument. However if this is not possible then I am open minded on every fast solution :)

War es hilfreich?

Lösung

Your span element is not a DomText object.

The spaces between the td start tag and the span start tag are the DomText object.

<td>
    <span class="emphasize" title="this modified">

Loop over the child nodes until you find the span, or use getElementsByTagName instead of childNodes.

Andere Tipps

This may help you

if ($td->nodeName === 'td') {                        
       $current[] = trim($td->nodeValue);
       $childOfTD = $td->childNodes->item(0);
       // print_r($childOfTD);
       // ====================== title ==================
       $title = $td->getElementsByTagName("span")->item(0)->getAttribute("title");
       echo $title;
       // ===============================================
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top