Reputation: 3308
Here is my code:
$url = "https://www.leaseweb.com/dedicated-servers/single-processor";
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTMLFile($url);
$xpath = new DOMXpath($doc);
$n = $xpath->query('//td[@data-column-name="Model"]');
$r = $xpath->query('//td[@data-column-name="RAM"]');
foreach ($n as $entry) {
$Name = $entry->nodeValue;
$RAM = $r->nodeValue;
echo " $Name - RAM: $RAM<br>";
}
I successfully echo $Name
but i can not get the value for $RAM
because i do not have it in my array. My question is how i can add $r
into this foreach loop and make it work ?
Thanks in advance!
Upvotes: 1
Views: 80
Reputation: 14423
PHP Documentation is kind of ambiguous at this point. DOMXPath::query
returns a DOMNodeList
which isn't really an Iterator
nor does it seems to implement ArrayAccess
but rather implements Traversable
which doesn't have a particular signature that's helpful to traverse the object.
Here's something that comes to mind:
$item = 0;
foreach ($n as $entry) {
$Name = $entry->nodeValue;
$RAM = $r->item($item)->nodeValue;
echo " $Name - RAM: $RAM<br>";
$item++;
}
Something else that might work:
$iterator = new IteratorIterator($r);
$iterator->rewind();
foreach ($n as $entry) {
$Name = $entry->nodeValue;
$node = $iterator->current();
$RAM = $node->nodeValue;
$iterator->next();
echo " $Name - RAM: $RAM<br>";
}
IteratorIterator class:
This iterator wrapper allows the conversion of anything that is Traversable into an Iterator. It is important to understand that most classes that do not implement Iterators have reasons as most likely they do not allow the full Iterator feature set. If so, techniques should be provided to prevent misuse, otherwise expect exceptions or fatal errors.
Upvotes: 1
Reputation: 2993
$i=0;
foreach ($n as $entry) {
$Name = $entry->nodeValue;
$RAM = $r[$i]->nodeValue;
echo " $Name - RAM: $RAM<br>";
$i++;
}
Upvotes: 0
Reputation: 4197
You could try with current and next array functions (php doc)
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTMLFile($url);
$xpath = new DOMXpath($doc);
$n = $xpath->query('//td[@data-column-name="Model"]');
$r = $xpath->query('//td[@data-column-name="RAM"]');
//Reset pointer to first element and assign to currR
$currR = reset($r);
foreach ($n as $entry) {
$Name = $entry->nodeValue;
$RAM = $currR->nodeValue;
echo " $Name - RAM: $RAM<br>";
//Move pointer to next element and assign this to currR
$currR = next($r);
}
Upvotes: 0
Reputation: 1473
use $key variable inside loop
foreach ($n as $key => $entry) {
$Name = $entry->nodeValue;
$RAM = $r[$key]->nodeValue;
echo " $Name - RAM: $RAM<br>";
}
Upvotes: 0