2011-04-03 93 views
0

嗨, 两个问题的DOMDocument类...php DOMDocument:在特定的ID中选择特定的类名?

我用jQuery这样做:

$('#wpf-wrapper .wpf-table .wpf-input').addClass('input-field'); 

我想要做同样与DOMDocument类!如何才能做到这一点?我怎样才能选择这个?

第二个问题是:为什么这不起作用?

$dom = new SmartDOMDocument(); 
$dom->loadHTML($shortcode); 
$xpath = new DOMXPath($dom); 

$qr = $dom->getElementById('quick-reply-submit'); 
//$qr->setAttribute('class', 'btn small width480'); 
//ERROR: Call to a member function on a non-object...?? 

谢谢你的帮忙!

+0

什么是smartdomdocument? – Gordon 2011-04-03 15:58:35

+0

它是一个非常有用的类,它扩展了DOMDocument类以获得更好的UTF-8支持等等。 – matt 2011-04-03 16:26:20

+0

关心在[最佳解析HTML方法]中提供与该lib的链接的答案(http://stackoverflow.com/问题/ 3577641 /最好的方法对语法分析HTML/3577662)?不能伤害它在那里。 – Gordon 2011-04-03 17:10:04

回答

1

您可以使用DOMXPath搜索您DOMDocument,然后遍历查询结果所需的值添加到class属性,如果它不存在:

// This is the equivalent of '#wpf-wrapper .wpf-table .wpf-input' 
$expr = '//*[@id="wpf-wrapper"]//*[@class="wpf-table"]//*[@class="wpf-input"]'; 

$result = $xpath->query($expr); 
for($i = 0; $i < $result->length; ++$i) { 
    // Get the classes of each matched element 
    $classes = explode(' ', $result->item($i)->getAttribute('class')); 

    // Add "input-field" if it's not in there already 
    if(!in_array('input-field', $classes)) { 
     $classes[] = 'input-field'; 
    } 

    // Set the class attribute to the new value 
    $result->item($i)->setAttribute('class', implode(' ', $classes)); 
} 

你的“第二个问题”的代码没有按”因为没有ID为quick-reply-submit的元素 - 没有其他可能性。

+0

谢谢你......最后一个问题。如何在一系列选择器中选择标记名,例如...例如。 '$ expr ='// * [@ id =“wpf-wrapper”] // * [@ class =“wpf-table”] // * [@ tagname =“a”]';'所以我想选择wpf-table中的所有锚点? – matt 2011-04-03 16:30:33

+0

@mathiregister:那个是'// * [@ class =“wpf-table”] // a'。查看更多的XPath语法教程,有很多很多的可能性。这里有一个:http://zvon.org/xxl/XPathTutorial/General/examples.html – Jon 2011-04-03 16:39:59