i have a structure that looks like this
<div class="table">
<div> <p> name1 </p> <p> title1 </p> </div>
<div> <p> name2 </p> <p> title2开发者_Python百科 </p> </div>
<div> <p> name3 </p> <p> title3 </p> </div>
</div>
and it continues a few hundred more times. what can i write in php that will search ( class="table" > div ) and add a class to only the first 'p' in each 'div'?
$str = '<div class="table">
<div> <p class="first"> name1 </p> <p> title1 </p> </div>
<div> <p> name2 </p> <p> title2 </p> </div>
<div> <p> name3 </p> <p> title3 </p> </div>
</div> ';
$dom = new DOMDocument;
$dom->loadHTML($str);
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//div[@class="table"]/div/p[position()=1]');
$addClass = 'first';
foreach($nodes as $node) {
if ($node->hasAttribute('class')) {
$classes = preg_split('/\s+/', $node->getAttribute('class'));
if (in_array($addClass, $classes)) {
continue;
}
} else {
$classes = array();
}
$classes[] = $addClass;
$node->setAttribute('class', implode(' ', $classes));
}
var_dump($dom->saveHTML());
Updated to not add first
twice :)
Output
string(340) "<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><div class="table">
<div> <p class="first"> name1 </p> <p> title1 </p> </div>
<div> <p class="first"> name2 </p> <p> title2 </p> </div>
<div> <p class="first"> name3 </p> <p> title3 </p> </div>
</div></body></html>
"
You may have noticed DOMDocument helpfully adds the HTML wrapper tags (html
, body
, etc) in for you.
You can get the body
element's inner HTML like so...
$output = '';
foreach($dom->getElementsByTagName('body')->item(0)->childNodes as $node) {
$output .= $dom->saveXML($node);
}
Output
<div class="table">
<div> <p class="first"> name1 </p> <p> title1 </p> </div>
<div> <p class="first"> name2 </p> <p> title2 </p> </div>
<div> <p class="first"> name3 </p> <p> title3 </p> </div>
</div>
Use PHP DOMDocument to traverse it and add attributes:
http://php.net/manual/en/class.domdocument.php
http://www.php.net/manual/en/domelement.setattribute.php
Cleaner way than string search.
There is a library called phpQuery
: http://code.google.com/p/phpquery/
You can walk through DOM object like with jQuery
:
phpQuery::newDocument($htmlCode)->find('div.table div')->find('p:first').attr('class', 'myVal');;
Would you consider doing this in javascript? You will find it much easier using something like YUI or JQuery
精彩评论