1

Could someone kindly help me get this parsed. I have the following XML. I need to get the value of photo-url that matches "75" max-width. How do I filter that in PHP $xml->posts->post['photo-url']....?

<photo-url max-width="100">
image1.jpg
</photo-url>

<photo-url max-width="75">
image2.jpg
</photo-url>

3 Answers 3

4

Using PHP DOM

$dom = new DomDocument;
$dom->loadXml('
<root>
    <photo-url max-width="100">image1.jpg</photo-url>
    <photo-url max-width="75">image2.jpg</photo-url>
</root>
');

$xpath = new DomXpath($dom);
foreach ($xpath->query('//photo-url[@max-width="75"]') as $photoUrlNode) {
    echo $photoUrlNode->nodeValue; // will be image2.jpg
}
Sign up to request clarification or add additional context in comments.

Comments

3

Use SimpleXMLElement and an xpath query.

$xml = new SimpleXMLElement($your_xml_string);
$result = $xml->xpath('//photo-url[@max-width="75"]');

// Loop over all the <photo-url> nodes and dump their contents
foreach ($result as $node ) {
   print_r($node);
   $image = strip_tags($node->asXML);
}

1 Comment

Woo, thanks! So my final usage was as following $img = $xml->xpath('//photo-url[@max-width="75"]'); echo '<img src="'.$img[0].'" />';
1

You can use XPath: //photo-url[@max-width = '75']. It will select all photo-url which satisfies this condition. To select only 1st photo-url use this: //photo-url[@max-width = '75'][1]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.