Help with 2 errors using DOMDocument for html parsing
When I run the decorate_keyword() function below, I'm getting two errors that I'm trying to resolve. The first seems the easiest to resolve. I'm getting...
Warning: DOMXPath::query() [domxpath.query]: Invalid expression in C:\xampplite\htdocs\testsite\wp-content\plugins\myplugin\index.php on line 48
Which points to the $nodes line in the function and is apparently stemming from the $keyword variable when it contains an empty space. $keyword = "test" does not throw the error. What do I need to change to overcome this error?
function rseo_decorate_keyword($postarray) {
$keyword = "test";
$content = $postarray['post_content'];
/*
even though I can echo $content and get a string,
I'm getting error: Empty string supplied in loadHTML() when I use this.
so, I have to explicity set it to a string as below to test.
*/
$content = "this is a test phrase";
$d = new DOMDocument();
$d->loadHTML($content);
$x = new DOMXpath($d);
$nodes = $x->query("//text()[contains(.,$keyword) and not(ancestor::h1) and not(ancestor::h2) and not(ancestor::h3) and not(ancestor::h4) and not(ancestor::h5) and not(ancestor::h6)]");
if ($nodes && $nodes->length) {
$node = $nodes->item(0);
// Split just before the keyword
$keynode = $node->splitText(strpos($node->textContent, $keyword));
// Split after the keyword
$node->nextSibling开发者_如何学Python->splitText(strlen($keyword));
// Replace keyword with <b>keyword</b>
$replacement = $d->createElement('b', $keynode->textContent);
$keynode->parentNode->replaceChild($replacement, $keynode);
}
$postarray['post_content'] = $d;
return $postarray;
}
The contains
XPath function should have the second argument in quotes if it contains various characters, such as ;&,
. The space is one of them.
$nodes = $x->query("//text()[contains(.,'$keyword') and not(ancestor::h1) and not(ancestor::h2) and not(ancestor::h3) and not(ancestor::h4) and not(ancestor::h5) and not(ancestor::h6)]");
For your mysql_real_escape_string
error, for some reason an object is being passed rather than a string. I'm not familiar with Wordpress internals: you should make a separate question with the appropriate tags.
精彩评论