Accessing @Attribute from Simplexml

Accessing @attribute from SimpleXML

You can get the attributes of an XML element by calling the attributes() function on an XML node. You can then var_dump the return value of the function.

More info at php.net
http://php.net/simplexmlelement.attributes

Example code from that page:

$xml = simplexml_load_string($string);
foreach($xml->foo[0]->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
}

Get an attribute value using SimpleXML for PHP

You can use the attributes() function on the node to get it's attributes:

$xml_str = '<xml>
<node>
<someTag cp="c2">content</someTag>
</node>
</xml>';
$res = simplexml_load_string($xml_str);

$items = $res->xpath("//someTag");
var_dump((string) $items[0]->attributes()->cp);

The returned element is an SimpleXMLElement, so in order to use it I converted it to string (using the (string) cast).

Access @attributes data in SimpleXMLElement in PHP

Did you try:

echo (string)$xml->product->attributes()->id;

That should give you access to the attributes.

If you have more than 1 product, it may be

echo (string)$xml->product[0]->attributes()->id;

You can also access the attributes using regular array notation such as:

$xml->product['id']; // instead of $xml->product->attributes()->id

See Example #5 from the SimpleXML Examples as well as the manual page on SimpleXMLElement::attributes() for more information.

accessing SimpleXML attribute

Because the elements are hyphenated you need to wrap them with {''}. Attributes are fine since they are accessed like an array, like ['doc-id']. It's the elements that you need to wrap if they contain a hyphen.

$scorexml->{'sports-content'}->{'sports-metadata'}['doc-id']

Check out example #3:
http://php.net/manual/en/simplexml.examples-basic.php

PHP SimpleXML + Get Attribute

This should work.

$id = $xml["id"];

Your XML root becomes the root of the SimpleXML object; your code is calling a chid root by the name of 'show', which doesn't exist.

You can also use this link for some tutorials: http://php.net/manual/en/simplexml.examples-basic.php

SimpleXml Get Attribute Value

Your main problem is that SimpleXML won't parse media:thumbnail. I wrote a quick solution for you, but I'm pretty sure there is a more efficient way of doing this:

header('Content-Type: text/html');

$rss = simplexml_load_string(
// replace media:thumbnail with mediathumbnail
str_replace(
'media:thumbnail',
'mediathumbnail',
file_get_contents($requestURL)
)
);

echo '<ul>';
foreach($rss->channel->item as $post)
{
echo '<li>';
// getting mediathumbnail attributes
$attributes = $post->mediathumbnail->attributes();
// this is the thumbnail url
$max = $attributes->url;
echo $max;
echo '<a href="'.$post->link.'">'.$post->title.'</a>';
echo '</li>';
}
echo '</ul>';

Hope I helped. :)



Related Topics



Leave a reply



Submit