0

我做错了什么让 xpath 没有收到任何东西?此函数在另一个深度稍差的 xml 文件上运行良好。

function xml2csv($xmlFile, $xPath) {
    $xml = simplexml_load_file($xmlFile);
    $path = $xml->xpath($xPath);
    $csvData = '';
    foreach($path as $item) {
        foreach($item as $key => $value) {
            $csvData .= '"' . trim($value) . '"' . ',';
        }
        $csvData = trim($csvData, ',');
        $csvData .= "\n";

    }
    return $csvData;
}

正在使用的 XML

<?xml version='1.0'?>
<bl>
    <section>
        <grade gradeLevel="1">
            <level dirname="The folder of pdfs">
                <file filename="hello_world.pdf">Hello world</file>
                <file filename="the_avengers.pdf">The Avengers</file>
                <file filename="batman.pdf">Batman</file>
            </level>
        </grade>
    </section>
</bl>

当调用xml2csv('test.xml', 'bl');什么都不返回时,与它之后的任何东西一样bl/section/grade/*等等,也尝试了单一目标。我希望至少输出文件名..

似乎工作得很好的 XML我可以使用上面相同的方法来定位下面的 xmlxml2csv('cars.xml', 'car');

<?xml version='1.0'?>
<cars>
    <car>
        <color>blue</color>
        <price>2000</price>
    </car>
    <car>
        <color>red</color>
        <price>10000</price>
    </car> 
    <car>
        <color>black</color>
        <price>5000</price>
    </car>
</cars>

汽车 XML 输出

"blue","2000"
"red","10000"
"black","5000"
4

1 回答 1

0

必须修改原始 xml2csv 函数才能关联。有针对性地使用section/grade.

更新功能仍在进行中

function xml2csv($xmlFile, $xPath) {
    $xml = simplexml_load_file($xmlFile);
    $path = $xml->xpath($xPath);
    $csvData = '';
    foreach($path as $item) {
        $attributes = $item->attributes();
        $gradeLevel = $attributes['gradeLevel'];
        foreach ($item->level as $level) {
            foreach ($level->file as $file) {
                $csvData .= '"' . trim($gradeLevel) . '"' . ',';
                $csvData .= '"' . trim($level->attributes()->dirname) . '"' . ',';
                $csvData .= '"' . trim($file->attributes()->filename) . '"' . ',';
                $csvData .= '"' . trim($file) . '"' . ',';
                $csvData .= "\n";

            }

        }
        $csvData = trim($csvData, ',');
        $csvData .= "\n";
    }
    return $csvData;
}
于 2013-01-15T23:36:16.173 回答