How to read SimpleXML Object in PHP


 
How can I properly parse a SimpleXML Object in PHP?

It is really simple to access attributes using array form. However, you must convert them to strings or ints if you plan on passing the values to functions.

You have to cast simpleXML Object to a string.

$value = (string) $xml->code[0]->lat;

If you know that the value of the XML element is a float number (latitude, longitude, distance), you can use (float)

$value = (float) $xml->code[0]->lat;

Also, (int) for integer number:

$value = (int) $xml->code[0]->distance;

You can more read about simplexmlelement.

If you have any queries, please do not hesitate to contact me at Jainish Senjaliya

Advertisements

How to read xml value with specific attribute


 

php getElementsByTagName with specific attribute

Read xml value with specific attribute

XML format is :

File Name = locallang_db.xml

<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<T3locallang>
    <meta type="array">
        <type>database</type>
        <description>Description..</description>
    </meta>
    <data type="array">
        <languageKey index="default" type="array">
            <label index="name">Jainish</label>
            <label index="surname">Senjaliya</label>
            <label index="dob">19-11-19XX</label>
            <label index="age">Top Secret</label>
        </languageKey>
    </data>
</T3locallang>	

Read XML File from PHP

$xmlPath = 'locallang_db.xml';
$objDOM = new DOMDocument('1.0', 'utf-8');
$objDOM->load($xmlPath); //make sure path is correct 
$label = $objDOM->getElementsByTagName("label"); 

foreach ($label as $val)
{
    if($val->getAttribute('index') === 'name')
    {
        echo  $val->nodeValue;
        // do something
    }
 // You can also get tag name by : $val->tagName OR $val->nodeName;
}		

OutPut :

 Jainish

Best Luck 🙂

If you have any query then feel free to contact me at Jainish Senjaliya