如何使用PHP

时间:2017-06-02 23:01:43

标签: php xml

我有一个XML文件,有300个元素。我只想从中提取10条最新记录并创建另一个XML文件。

如果你能给我一些关于它的想法,我将非常感激吗?

PHP

$file = '/directory/xmlfile.xml';
if(!$xml = simplexml_load_file($file)){
    exit('Failed to open '.$file);
} else{
    print_r($xml);
    // I want to do some logic here to retrieve top 10 records from file and then create another xml file with 10 records
}

XML示例数据

<data>
    <total>212</total>
    <start>0</start>
    <count>212</count>
    <data>
        <item0>
            <id>123</id>
            <title>abc-test1</title>
            <clientContact>
                <id>111</id>
                <firstName>abc</firstName>
                <lastName>xyz</lastName>
                <email>abc@xyz.ca</email>
            </clientContact>
            <isOpen>1</isOpen>
            <isPublic>1</isPublic>
            <isJobcastPublished>1</isJobcastPublished>
            <owner>
                <id>222</id>
                <firstName>testname</firstName>
                <lastName>testlastname</lastName>
                <address>
                    <address1>test address,</address1>
                    <address2>test</address2>
                    <city>City</city>
                    <state>state</state>
                    <zip>2222</zip>
                    <countryID>22</countryID>
                    <countryName>Country</countryName>
                    <countryCode>ABC</countryCode>
                </address>
                <email>test@test.com</email>
                <customText1>test123</customText1>
                <customText2>testxyz</customText2>
            </owner>
            <publicDescription>
                <p>test info</p>
            </publicDescription>
            <status>test</status>
            <dateLastModified>22222</dateLastModified>
            <customText4>test1</customText4>
            <customText10>test123</customText10>
            <customText11>test</customText11>
            <customText16>rtest</customText16>
            <_score>123</_score>
        </item0>
        <item1>
        ...
        </item1>
        ...
    </data>
</data>

1 个答案:

答案 0 :(得分:1)

考虑XSLT,这是专门用于将XML转换/操作到各种最终用途的专用语言,例如提取前十个<item*>标记。无需foreachif逻辑。 PHP维护一个可以在.ini文件(php-xsl)中启用的XSLT处理器。

具体来说,XSLT运行Identity Transform来复制文档,然后为位置超过10的 item 节点写一个空白模板。由于父/子相同,XML有点困难{ {1}}代码。

XSLT (另存为.xsl文件,格式正确的xml)

<data>

PHP

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@*|node()">  
        <xsl:copy> 
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="*[substring(name(),1,4)='item' and position() &gt; 10]"/>   

</xsl:stylesheet>