tags:

views:

57

answers:

1

Similar question from last night, I don't have access to edit the source HTML and I am attempting to parse a lot of data from a website to do product price/comparisons against. For the most part, it's working but I am now trying to make it more efficient, faster and easier to read my spaghetti code.

I have the following test code; and what I am wanting to do is only return the attribute for content (e.g. thisiswhatiwant) if the nodeValue for productType is Stocked and nothing else.

<div id="productListing">

<div class="productDetail">
    <span class="productType">Stocked</span>: <span class="productStock"><span class='productContent' content='thisiswhatiwant'></span></span>
</div>

<div class="productDetail">
    <span class="productType">Non-stocked</span>: <span class="productStock"><span class='productContent' content='xyz'></span></span>
</div>

…

<div class="productDetail">
    <span class="productType">Non-stocked</span>: <span class="productStock"><span class='productContent' content='123'></span></span>
</div>

</div>

This is the Xpath query I have such far, but I am either missing something vital or something in my brain just hasn't clicked into gear yet.

//div[@id="productListing"]/div[@class="productDetail"]/span[@class="productStock"]/preceding-sibling::span[text()="Stocked"]

Basically, what I want to output from the above test code is:

<?
echo "Output: " . $dom->getAttribute('content');
?>

Output: thisiswhatiwant

Anyone got any ideas?

+2  A: 

Assumig that $dom is the DomDocument object created from the given XML string:

$xpath = new DOMXPath($dom);
$q = '//span[@class="productType" and text()="Stocked"]/ancestor::*[@class="productDetail"]/span[@class="productStock"]/span[@class="productContent"]';
$res = $xpath->query($q);
foreach($res as $node) {
    echo $node->getAttribute('content') . PHP_EOL;
}
nuqqsa
That did it! Thank you.
Michael Pasqualone