How can multiple segments with the same name be addressed and read in an XML file using PHP?

When dealing with multiple segments with the same name in an XML file, it can be challenging to address and read them individually using PHP. One way to solve this issue is by using XPath queries to target specific segments based on their parent node or other unique identifiers within the XML structure.

$xml = simplexml_load_file('file.xml');

// Use XPath to target specific segments with the same name
$segments = $xml->xpath('//parent/segment[@name="segmentName"]');

// Loop through the selected segments and read their values
foreach ($segments as $segment) {
    echo $segment->value . "\n";
}