douxu0550 2013-01-02 15:46
浏览 34
已采纳

将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 08: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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器