douxu0550 2013-01-02 07:46
浏览 35
已采纳

将xPath变为变量

How do I turn the output into a variable so i can cross reference it to see if it matches another variable I have set

foreach ($nodes as $i => $node) {
  echo $node->nodeValue;
}

I know this is incorrect and wouldn't work but:

foreach ($nodes as $i => $node) {
  $target = $node->nodeValue;
}

$match = "some text"

if($target == $match) {
  // Match - Do Something
} else {
  // No Match - Do Nothing
}

Actually this solves my question but maybe not the right way about it:

libxml_use_internal_errors(true);
$dom = new DomDocument;
$dom->loadHTMLFile("http://www.example.com");
$xpath = new DomXPath($dom);
$nodes = $xpath->query("(//tr/td/a/span[@class='newprodtext' and contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'adidas')])[1]");
foreach ($nodes as $i => $node) {

echo $node->nodeValue, "
";
$target[0] = $node->nodeValue;
}

$match = "adidas";

if($target == $match) {
    // Match
} else {
    // No Match
}

展开全部

  • 写回答

1条回答 默认 最新

  • duanliang1019 2013-01-03 00:15
    关注

    Your problem is more about general understanding of loops, assigning values to arrays and using if conditionals with php than using xpath.

    • In your foreach loop, you're assigning each $node's nodeValue to the same index in your $target array, $target will always have only one value (the last one)
    • In your if conditional statement, you're comparing an array (or null if $nodes has no items, so you probably want to declare $target first) against the string 'adidas', that will never be true.

    You probably want to do something like:

    $matched = false;
    $match = 'adidas';
    foreach ($nodes as $i => $node) {
        $nodeValue = trim(strip_tags($node->textContent));
        if ($nodeValue === $match) {
            $matched = true;
            break;
        }
    }
    
    if ($matched) {
        // Match
    } else {
        // No Match
    }
    

    Update

    I see that this xpath expression was given to you in another answer, that presumably already does the matching, so you just need to check the length property of $nodes

    if ($nodes->length > 0) {
        // Match
    } else {
        // No match
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?