简体   繁体   中英

Filter an XML file

I'm attempting to use a form to filter an XML file and am having toruble using xpath to get the desired results.

<?php
$filterHeading = 'CD';
$filterText = '1989';

$filename = "xml/xml_cd.xml";
$xml = simplexml_load_file($filename);

echo 

$result = $xml->xpath('//' + $filterHeading + '[YEAR="' + $filterText + '"]');

print_r($result);


?>

My aim is to use this PHP script to eventually take the variables (heading/text) from the webpage and display in JSON format. However I am unable to get the XML filter itself to work - any ideas?

Thanks in advance!

EDIT

XML

<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
</CATALOG>

The node YEAR itself isn't equal to 1989 , the text in it is. So

//CD[YEAR/text()="1989"]

will do the trick. In your code:

$result = $xml->xpath('//'.$filterHeading.'[YEAR/text()="'.$filterText.'"]');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM