Simplexml Get Attributes with a Namespace

How to get attribute of node with namespace using SimpleXML?

So I found a way to do it using xpath, is this the best way or is there a way that's consistent with my code in the question? Just out of curiosity.

$source = 'youtube.xml';

// load as file
$youtube = new SimpleXMLElement($source, null, true);
$youtube->registerXPathNamespace('yt', 'http://gdata.youtube.com/schemas/2007');

$count = 0;
foreach($youtube->entry as $item){

//title works
echo $item->title;

$attributes = $item->xpath('//yt:duration/@seconds');
echo $attributes[$count]['seconds'];
$count++;
}

Simplexml get attributes with a namespace

You need to use the namespace when getting the attribute. The android namespace is defined as:

http://schemas.android.com/apk/res/android

So you need to pass that to the attributes() method, like this:

$xml = simplexml_load_string($xmlStr);

echo (string) $xml->application->activity->attributes('http://schemas.android.com/apk/res/android')->name;

Outputs

com.sunil.tweet.MainActivity

Codepad Demo

SimpleXML namespaces and attributes

Using

->children();

at the end, that is with the default namespace, will give you a child-collection of zero elements. As it's empty, SimpleXML internally runs some optimizations. Accessing it again might lead to errors:

$nodes->attributes()['value']

Warning: main(): Node no longer exists in ...

Perhaps the best way is to just leave it out and name the children you're looking for:

$nodes = ... ->extension->children($namespaces["keyvalue"])->kv;

print_r($nodes[1]->attributes()['value']);

Gives this output:

SimpleXMLElement Object
(
[0] => ZBh5ralfPl
)

As it's the second <kv> element (zero-based) of which the attribute "value" is accessed.

If you want to leave the concrete element out of it, just leave it out (do not add ->children()). The same example:

$nodes = $xml->response->extension->children($namespaces["keyvalue"])->
extension->children($namespaces["keyvalue"]);

print_r($nodes[1]->attributes()['value']);

This gives exactly the same output:

SimpleXMLElement Object
(
[0] => ZBh5ralfPl
)

as there are only <kv> elements as children there, so the numbering does not change.

Hope this helps to shed some light. Perhaps better than all this is to use xpath:

$xml->registerXPathNamespace('kv', $namespaces["keyvalue"]);

var_dump($xml->xpath('//kv:kv[@key = "AUTH"]/@value')[0]);

Which gives:

class SimpleXMLElement#6 (1) {
public $@attributes =>
array(1) {
'value' =>
string(10) "ZBh5ralfPl"
}
}

Xpath is specialized on traversal. This is even better when it comes to namespaces.

Pulling SimpleXML Attributes with Namespaces

You could register the namespace first and get the desired results with a single xpath query:

$xml = simplexml_load_string($response);
$xml->registerXPathNamespace('urn', 'urn:com:esi911:webeoc7:api:1.0');
$records = $xml->xpath('//urn:record');

echo (string)$records[0]->attributes()->dataid;

Demo: https://3v4l.org/f8faC

Note: you could be more accurate and use something like //urn:GetDataResult/urn:data/urn:record (instead of the shorter //urn:record) as the XPath query, in case there can be records at another place within the XML you receive.

XML - getting value from namespace using SimpleXML

The children() method doesn't return some kind of token for the namespace, it returns a list of elements - the children which are in the given namespace.

The $xml variable represents the top-level message element, which doesn't have any children in the http://www.blendlabs.com namespace, so $xml->children('http://www.blendlabs.com') will just return an empty list. You need to first navigate to the other element, and then get its children in the http://www.blendlabs.com namespace, which will include the loan element.

Since the top level element is in the http://www.mismo.org/residential/2009/schemas namespace, you might need an extra children() call to make sure you select that first.

You didn't provide a complete XML, so I can't test the code (I don't fancy manually writing all those close tags), but it will look something like this:

$marketing_value = (string)
$xml
->children('http://www.mismo.org/residential/2009/schemas')
->deal_sets->deal_set->deals->deal->loans->loan->extension->other
->children('http://www.blendlabs.com')
->loan->marketing_items->marketing_item->marketingvalue;

Access attributes of XML node with namespace in PHP

I solved it, I found the solution at http://bytes.com/topic/php/answers/798486-simplexml-how-get-attributes-namespace-xml-vs-preg_

foreach($x->y->z[0]->w->k as $k){                 
$namespaces = $k->getNameSpaces(true);
$xsi = $k->attributes($namespaces['xsi']);

echo $xsi['type'];
}

The getNameSpaces(true) function returns the namespaces of the XML document, then I select the one I'm looking for (xsi) and access the attribute I need like if the attributes is of the namespaces, and not of the $k node. I wish this can help someone else.

SimpleXML children's attributes behaves different with and without namespace

The reason for this is not actually anything to do with SimpleXML, but to do with some surprising details of how XML namespaces work, according to the standard.

In your example, you have a namespace declared with the prefix a, so to declare that an attribute is in that namespace, you must prefix its name with a:, just as you do with elements:

<a:child a:role="daughter"/>

It seems to be a common assumption that an attribute without a namespace prefix is in the same namespace as the element it is on, but that is not the case. The example above is not equivalent to your example:

<a:child role="daughter"/>

Another case you might see is where there is in a default (unprefixed) namespace:

<person xmlns="http://example.com/foo.bar"><child role="daughter" /></person>

Here, the child element is in the http://example.com/foo.bar namespace, but the role attribute still isn't! As discussed in this related question, the relevant section of the XML Namespaces spec includes this statement:

The namespace name for an unprefixed attribute name always has no value.

That is, an attribute with no namespace prefix is never in any namespace, regardless of what the rest of the document looks like.

So, what effect does this have on SimpleXML?

SimpleXML works on the basis of altering the "current namespace" whenever you use the ->children() or ->attributes() methods, and tracking it from then on.

So when you write:

$children = $xml->children('a', true);

or:

$children = $xml->children('http://example.com/foo.bar');

the "current namespace" is foo:bar. Subsequent use of the ->childElement or ['attribute'] syntax will look in this namespace - you don't need to call children() again every time - but your unprefixed attributes won't be found there, because they have no namespace.

When you subsequently write:

$attributes = $children->attributes();

this is interpreted the same way as:

$attributes = $children->attributes(null);

So now, the "current namespace" is null. Now when you look for the attributes which have no namespace, you will find them.



Related Topics



Leave a reply



Submit