Michal Vlasák
Michal Vlasák

Reputation: 247

Xpath path doesn't work

I have the following XML:

<root>
    <product>
        <code>ZX-0015</code>
        <attached_files>
            <file>
                <type>images_800x600</type>
                <url>http://www.example.com/img/800_600/ZX-0015.jpg</url>
            </file>
            <file>
                <type>images_300x200</type>
                <url>http://www.example.com/img/300_200/ZX-0015.jpg</url>
            </file>
        </attached_files>
    </product>
    <product>
        <code>02PX-5836</code>
        <attached_files>
            <file>
                <type>images_800x600</type>
                <url>http://www.example.com/img/800_600/02PX-5836.jpg</url>
            </file>
            <file>
                <type>images_300x200</type>
                <url>http://www.example.com/img/300_200/02PX-5836.jpg</url>
            </file>
        </attached_files>
    </product>
</root>

I try to read the information with php xpath. I need to display product's url with type 'images_800x600'.

I tried:

foreach($xml as $item){
    $sku = $item->code;
    $x_img = $xml->xpath("//file[type='images_800x600' and ./code='$sku']/url");
   // I also tried
   $x_img = $xml->xpath("//file[type='images_800x600' and ./code='$sku']/following-sibling::url");
   var_dump($x_img);
}

But I only get following output:

array(0) { } array(0) { }

How to get the requested url with type 800x600?

Upvotes: 0

Views: 57

Answers (2)

Felipe Weckx
Felipe Weckx

Reputation: 11

Another option is, since you're iterating each product item, you can do a relative xpath query:

foreach ($xml as $item) {
    $sku = $item->code;
    $x_img = $item->xpath("attached_files/file[type='images_800x600']/url");
    var_dump($x_img);
}

And on each item you fecth the image of the desired size.

Upvotes: 0

Martin Honnen
Martin Honnen

Reputation: 167471

Try xpath("//product[code='$sku']//file[type='images_800x600']/url");.

Upvotes: 1

Related Questions