PHP - SimpleXML

From XennisWiki
Jump to: navigation, search

Work with XML files in PHP

Doppelpunkt

Problem

Mit SimpleXML kann man nicht ohne weiteres Ausdrücke mit einem Doppelpunkt auslesen

<gphoto:user>

Lösung

Doch wie folgt kann man das Problem lösen:

Beispiel.xml

<?xml version='1.0' encoding='UTF-8'?>
<feed
  xmlns='http://www.w3.org/2005/Atom'
  xmlns:gphoto='http://schemas.google.com/photos/2007'
  xmlns:media='http://search.yahoo.com/mrss/'
  xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'>
	<id>123456</id>
	<updated>2010-08-05T16:17:42.502Z</updated>
	<openSearch:totalResults>5</openSearch:totalResults>
	<gphoto:user>Lenny</gphoto:user>
	<entry>
		<media:group>							
			<media:credit>Carl</media:credit>>
		</media:group>
	</entry>
	<entry>
</feed>

Durch folgenden PHP Code ...

$xml_file = simplexml_load_file('Beispiel.xml');
$xml_file->registerXPathNamespace('gphoto', 'http://schemas.google.com/photos/2007');
$xml_file->registerXPathNamespace('media', 'http://search.yahoo.com/mrss/');
$xml_file->registerXPathNamespace('openSearch', 'http://a9.com/-/spec/opensearchrss/1.0/');

echo array_pop($xml_file->xpath('//openSearch:totalResults'));
echo array_pop($xml_file->$entry->xpath('//gphoto:user'));
echo array_pop($entry->xpath('//media:keywords'));

... erhält man die Ausgabe

5
Lenny
Carl

Um sich diesen Teil ...

$xml_file->registerXPathNamespace('gphoto', 'http://schemas.google.com/photos/2007');
$xml_file->registerXPathNamespace('media', 'http://search.yahoo.com/mrss/');
$xml_file->registerXPathNamespace('openSearch', 'http://a9.com/-/spec/opensearchrss/1.0/');

... zu sparen:

// Get namespaces declared in document
$xml_namespaces = $xml_file->getDocNamespaces();
	// Register xpath namespace
	while($namespace = current($xml_namespaces)) {
		if(key($xml_namespaces) != "") {
			$xml_file->registerXPathNamespace(key($xml_namespaces), $namespace);
		}
		next($xml_namespaces);
	}

See also

External links