How to Get the Value of an Attribute from Xml File in PHP

How to get the value of an attribute from XML file in PHP?

You should be able to get this using SimpleXMLElement::attributes()

Try this:

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

That will show you all the name/value attributes for the first foo element. It's an associative array, so you can do this as well:

$attr = $xml->Var[0]->attributes();
echo $attr['VarNum'];

Using PHP to Parse XML to get Attribute values?

Is there a particular reason you must use SimpleXML? if none, you could try with DOMDocument instead. Code is below:

$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->load('example.xml');

$properties = $dom->getElementsByTagName('property');
foreach($properties AS $property)
{
$value = $property->nodeValue;
$type = $property->getAttribute('type');
echo '<div>Node Information/Value :'. $value. '<br/>'. 'Node attribute:'. $type. '</div>';
}

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).

How to get value from XML id - PHP

It might not be the most efficient (you have to go through each PARAM element until the desired one is found, which could be many), but this will get the job done.

$x = simplexml_load_string($xmlString);

foreach($x->PARAMETER->PARAM as $param){

if((string)$param->attributes()->ID == "sitPag")
{
echo (string)$param->attributes()->VALUE;
break;
}
}

DEMO

PHP - get value of an XML attribute

<?php

$xmlDoc=new DOMDocument();
$xmlDoc->load('source.xml');

$properties = $xmlDoc->getElementsByTagName('property');
$first_property = $properties->item(0);
echo "$first_property->tagName\n";

$first_property_children = $first_property->childNodes;
echo $first_property_children->length;

/*
for ($j=4;$j<($cd->length);$j++) {
echo ("<div>" . $c->item($j)->attributes()->description . "</div>");
echo ("<div>" . $c->item($j)->childNodes["description"] . "</div>");
echo ("<div>" . $c->item($j)["description"] . "</div>");
}
*/
?>

--output:--
property
9

9??!! Wtf?! Here's what your xml file really looks like:

<property>\n  #<==SEE THIS??
<name>a</name>\n #<==AND HERE??
<description>aaa</description>\n
<example value="b" description="bbb">b1</example>\n
<example value="c" description="ccc">c1</example> \n
</property>

When you hit Return in a text file, an invisible newline character is entered into the file. Every one of the newlines is considered by xml to be enclosed in an invisible text node. Because there are 5 text nodes created by the 5 newlines inside the property tag, as well as the 4 other visible nodes, there are a total of 9 children in the property tag.

In your loop, so as to only land on the visible elements, you could start at childNodes[1] (skipping the first newline text node), and then skip every other childNode:

for ($j=1; $j<($property_children->length); $j += 2) {

echo ("<div>" . $property_children->item($j)->nodeValue . "</div>\n");

//echo ("<div>" . $first_property_children->item($j)->nodeValue . "</div>");
//echo ("<div>" . $first_property_children->item($j)->childNodes["description"] . "</div>");
//echo ("<div>" . $first_property_children->item($j)["description"] . "</div>");
}

?>

--output:--
<div>a</div>
<div>aaa</div>
<div>b1</div>
<div>c1</div>

That gives you the text of all the visible tags.

Instead of looping, you can figure out the position of the description tag in the childNodes array. Here is where your description tag is located in the childNodes array:

                    +- from the spaces at the start of the next line
|
0 V 1 2 3
<property><text>\n </text><name>a</name><text>\n </text><description>aaa</description>....

So, you can write:

echo $property_children->item(3)->nodeValue;  //nodeValue gives you the text 

--output:--
aaa

But having to count nodes and take into account invisible text nodes created by whitespace inside a tag is too much of a hassle for us poor programmers, so there are other ways of obtaining a child node:

<?php

if ($property = simplexml_load_file('source.xml') )
{
//Grab all the child description tags in an Array:
echo $property->description[0] . "\n";

//Doing the same thing with xpath(which treats xml like a directory structure on your computer):
echo $property->xpath('./description')[0] . "\n";

}

?>


--output:--
aaa
aaa

See Basic SimpleXML usage in the php docs.

I want to return an attribute description.

An attribute? You mean the description attributes for all the example tags?

You can treat a tag like it is an array and use the attribute name as the subscript:

<?php

if ($property = simplexml_load_file('source.xml') )
{

$example_tags = $property->example;

foreach($example_tags as $example_tag) {
echo $example_tag['description'];
}

}

?>
--output:--
bbb
ccc

Here it is with xpath:

<?php

if ($property = simplexml_load_file('source.xml') )
{

$description_attrs = $property->xpath('./example/@description');

foreach($description_attrs as $description_attr) {
echo "$description_attr\n";
}


}

?>

--output:--
bbb
ccc

How to get the value of an attribute inside an XML element in PHP?

Use the SimpleXML extension:

<?php
$xml = '<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
</bookstore>';
$doc = simplexml_load_string($xml);
echo $doc->book->attributes()->category; // cooking
echo $doc->book->title.PHP_EOL; // Everyday Italian
echo $doc->book->title->attributes()->lang.PHP_EOL; // en

Demo

Every element will be set as a property on the root object for you to access directly. In this particular case, you can use attributes() to get the attributes of the book element.

You can see in the example that you can keep going through the levels in the same way: to get to the lang attribute in book, use $doc->book->title->attributes()->lang.

Get attribute value in SimpleXML object by element and another attribute value

You can use SimpleXML's xpath method to return an attribute of a node based on the value of another attribute:

$sxml = simplexml_load_string($xml);

$rate = (float) $sxml->xpath('./currencies/currency[@id="EUR"]/@rate')[0];

echo $rate;

Note that the method will always return an array, so we need to ask for the first element, and then cast the value to a float.

See https://eval.in/957883 for a full example

PHP SimpleXML - Get Attribute Values - Loop

You could try something like this :

$xml=simplexml_load_file("http://2strok.com/gen/maler.xml") or
die("Error: Cannot create object");
foreach($xml->ResultList->XResult as $res) {
if ($res->Contacts->XContact) {
echo $res->Contacts->XContact->Name . "<br>";
echo $res->Contacts->XContact->Value . "<br>";
echo $res->Contacts->XContact->VisitationAddress . "<br>";
}
}

Or this, if you want all contacts :

$xml=simplexml_load_file("http://2strok.com/gen/maler.xml") or
die("Error: Cannot create object");
foreach($xml->ResultList->XResult as $res) {
foreach ($res->Contacts->XContact as $elm) {
echo $elm->Name . "<br>";
echo $elm->Value . "<br>";
echo $elm->VisitationAddress . "<br>";
}
}


Related Topics



Leave a reply



Submit