Php XML到CSV=参数无效

Php XML到CSV=参数无效,php,xml,parsing,Php,Xml,Parsing,您好,我有以下从远程站点返回的xml结果 <ResultSet totalResultsAvailable="1"> <Product orderNo="5321" partNo="A2345" truckable="1"> <Manufacturer id="22">WIDGET 4 U</Manufacturer> <Model id="356">ACME 500</Model> <Years>

您好,我有以下从远程站点返回的xml结果

<ResultSet totalResultsAvailable="1">
  <Product orderNo="5321" partNo="A2345" truckable="1">
  <Manufacturer id="22">WIDGET 4 U</Manufacturer>
  <Model id="356">ACME 500</Model>
  <Years>95-98</Years>
  <ProductType id="23" categoryID="4">Cool Red Widgest</ProductType>
  <Material id="6">shiny stuff</Material>
  <PartNo>A2345</PartNo>
  <Code/>
</Product>
</ResultSet>
这是我的密码:

<?
echo 'Write XML to CSV';
$basenameLong ='http://thisIsTheURLto.com/myFeed/?key=123456789&mode=getProducts;
$fileNameCSV = 'xmlParseContent.csv';

$feedContent = '';    
echo '<br/>Starting......';     
$feedContent = file_get_contents($basenameLong);

$fh = fopen($fileNameCSV, 'w+'); //create new CSV file if not exists else append

foreach($feedContent->ResultSet->Product as $product) {

    fputcsv($f, get_object_vars($product),',','"');
}
fclose($fh);


?>
这行是错误的:

fputcsv($f, get_object_vars($product),',','"');
如果要输入空白值,请尝试执行以下操作:

fputcsv($f, get_object_vars($product),'','','');

您的问题是您从未解析XML文件。用
simplexml\u load\u file
替换
file\u get\u contents
,它应该可以工作。

使用PHP将XML转换为CSV相当容易,至少在我目前遇到的情况下是这样。在我的例子中,如果我可以简单地将结构化XML数据转换为CSV数据,这将为我节省大量的工作。通常,我只想转换原始XML文档的特定xpath中的数据。下面的PHP函数将加载一个XML文件,并将指定xpath中的元素转换为简单的csv数据

function xml2csv ($xmlFile, $xPath) {

    // Load the XML file
    $xml = simplexml_load_file($xmlFile);

    // Jump to the specified xpath
    $path = $xml->xpath($xPath);

    // Loop through the specified xpath
    foreach($path as $item) {

        // Loop through the elements in this xpath
        foreach($item as $key => $value) {

            $csvData .= '"' . trim($value) . '"' . ',';

        }

        // Trim off the extra comma
        $csvData = trim($csvData, ',');

        // Add an LF
        $csvData .= "\n";

    }

    // Return the CSV data
    return $csvData;

}

我的目标是创建一个导入excel的文件,其中的列包含以下节点的数据:OrderNo | partNO | Manufacturer id | Model | Years | ProductType id | Product Type CategoryID | Material | partNO不需要标题,只需要seprate列或选项卡中用一些疯狂的东西,比如~~^这样我就可以导入了。我试着自学,我认为我走上了正确的道路,但就在第一部分就失败了。这就是我作为指导的内容:我发现了一些拼写错误并修复了它们,但仍然有问题。这是我的新密码。
function xml2csv ($xmlFile, $xPath) {

    // Load the XML file
    $xml = simplexml_load_file($xmlFile);

    // Jump to the specified xpath
    $path = $xml->xpath($xPath);

    // Loop through the specified xpath
    foreach($path as $item) {

        // Loop through the elements in this xpath
        foreach($item as $key => $value) {

            $csvData .= '"' . trim($value) . '"' . ',';

        }

        // Trim off the extra comma
        $csvData = trim($csvData, ',');

        // Add an LF
        $csvData .= "\n";

    }

    // Return the CSV data
    return $csvData;

}