Parsing XML: xpath attributes
Here are two examples of getting attribute values using an xpath query: one using simpleXML and one using DOM document. Both queries are on namespaces within the XML file.
First here’s the DOM Document version:
$dom = new DomDocument();
// it's possible to use the static method ::load instead of intantiating
$dom->load('http://api.flickr.com/services/feeds/groups_pool.gne?id=12345678@N00&format=rss_200');
$xpath = new DOMXPath($dom);
$result = $xpath->query("//media:thumbnail/@url");
foreach ($result as $val) {
// make an array of thumbnail URLs from a Flickr group
$thumbsArray[] = $val->nodeValue;
}
… and the SimpleXML version:
$xml = simplexml_load_file('http://api.flickr.com/services/feeds/groups_pool.gne?id=12345678@N00&format=rss_200');
$result = $xml->xpath('//media:thumbnail/@url');
foreach ($result as $val) {
// make an array of thumbnail URLs from a Flickr group
$thumbsA[] = (string)$val['url'];
}
No comments yet
