1

I'm attempting to extract the date saved in the <PersonDetails> tag for some XML I am working with, example:

 <Record> <PersonDetails RecordDate="2017-03-31T00:00:00"> <FirstName>Joe</FirstName> <Surname>Blogs</Surname> <Status>Active</Status> </PersonDetails> </Record> 

Currently I have been trying the following:

if (isset($XML->Record->xpath("//PersonDetails[@RecordDate]")[0])) { $theDate = $XML->Record->xpath("//PersonDetails[@RecordDate]")[0])->textContent; } else { $theDate = "no date"; } 

My intention is to have $theDate = 2017-03-31T00:00:00

2 Answers 2

2

A valid XPath expression for selecting attribute node should look like below:

$theDate = $XML->xpath("//Record/PersonDetails/@RecordDate")[0]; echo $theDate; // 2017-03-31T00:00:00 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Roman, I got this to work thanks to you. Just out of interest, I kept using this 'semi' xpath: $XML->Record->xpath("//PersonDetails[@RecordDate]")[0]) just changing it to: $XML->Record->xpath("//PersonDetails/@RecordDate")[0]) and it worked perfectly.
1

You're mixing SimpleXML and DOM here. Additionally the expression fetches a PersonDetails element that has a RecordDate attribute. [] are conditions.

SimpleXML

So to fetch attribute node you need to use //PersonDetails/@RecordDate. In SimpleXML this will create a SimpleXMLElement for a non existing element node that will return the attribute value if cast to a string. SimpleXMLElement::xpath() will always return an array so you need to cast the first element of that array into a string.

$theDate = (string)$XML->xpath("//PersonDetails/@RecordDate")[0]; 

DOM

$textContent is a property of DOM nodes. It contains the text content of all descendant nodes. But you don't need it in this case. If you use DOMXpath::evaluate(), the Xpath expression can return the string value directly.

$document = new DOMDocument(); $document->loadXml($xmlString); $xpath = new DOMXpath($document); $theDate = $xpath->evaluate('string(//PersonDetails/@RecordDate)'); 

The string typecast is moved into the Xpath expression.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.