0

I have an XML file I need to parse that looks similar to the below:

<directory name="Addbriefs">
<file name="File1.pdf"/>
<file name="File2.pdf"/>
<file name="File3.pdf"/>
<file name="File4.pdf"/>
</directory>

<directory name="Addusefulinfo">
<file name="FileA.pdf"/>
<file name="FileB.pdf"/>
<file name="FileC.pdf"/>
<file name="FileD.pdf"/>
</directory>

<directory name="Newbriefs">
<file name="FileZ.pdf"/>
<file name="FileY.pdf"/>
<file name="FileX.pdf"/>
<file name="FileW.pdf"/>
</directory>

I'm using PHP and want to be able to return a string which contains all of the name attributes for all file elements, but only if the name attribute of the parent element (directory) matches a variable that I define elsewhere.

i.e. if $var = "Newbriefs", I want to return the below string...

FileZ.pdf FileY.pdf FileX.pdf FileW.pdf

I successfully use simplexml elsewhere in my PHP code on the same website, but so far only to return a string of all attributes of a specific element type, not based on what the parent element attribute is. I've checked and I'm not sure simplexml has the capabilities to achieve this? Thanks

1 Answer 1

1

You can do this fairly simply with SimpleXML's xpath method:

$var = "Newbriefs";
$files = $sxml->xpath("directory[@name='$var']/file/@name");

This query filters the <directory> tags to those with name="Newbriefs", and then return the name attribute from all child <file> elements.

You can treat each element in the $files array as you would a normal SimpleXMLElement object - just cast it to string to get the contents:

$filename = (string) $files[0]; // FileZ.pdf

See https://eval.in/877375

Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant, just tested this and managed to get it working straight away. Thanks very much for your prompt assistance, it's very much appreciated!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.