Reputation: 589
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, "\n";
$target[0] = $node->nodeValue;
}
$match = "adidas";
if($target == $match) {
// Match
} else {
// No Match
}
Upvotes: 0
Views: 355
Reputation: 1355
Your problem is more about general understanding of loops, assigning values to arrays and using if conditionals with php than using xpath.
$node
's nodeValue
to the same index in your $target
array, $target
will always have only one value (the last one)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
}
Upvotes: 1