0

以下是代码,我正在尝试将从 xml 文件中提取的数据格式化为 csv。默认情况下,它的插入行是明智的。我试图让它看起来像并且易于解释。我不是专业的编码员,所以如果我的解决方案不是优化的,请见谅。

<?php
header('Content-Type: application/excel');
header('Content-Disposition: attachment; filename="DynaMedResult.csv"');

//Using esearch utility capture WebEnv variable
$url= "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term=DynaMed&usehistory=y&retmode=xml";
$xml = file_get_contents($url, false, $context); //Reads entire file into a string
$xml = simplexml_load_string($xml);

foreach ($xml->WebEnv as $WebenvSearch){
   $WebEnv=$WebenvSearch;  
}
//Using efetch utility and passing WebEnv variable parse the xml
$url= "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&term=DynaMed&WebEnv=$WebEnv&query_key=1&usehistory=y&retmode=xml";
$xml = file_get_contents($url, false, $context);
$xml = simplexml_load_string($xml); //Interprets a string of XML into an object
$fp = fopen('php://output', 'w');

foreach ($xml as $pubmedst){
    $article=$pubmedst->MedlineCitation->Article->ArticleTitle;
    $pmid=$pubmedst->MedlineCitation->PMID;
    $journal1=$pubmedst->MedlineCitation->MedlineJournalInfo->MedlineTA;
    $journal2=$pubmedst->MedlineCitation->MedlineJournalInfo->NlmUniqueID;
    $pubyear=$pubmedst->MedlineCitation->Article->Journal->JournalIssue->PubDate->Year;
    $pubmonth=$pubmedst->MedlineCitation->Article->Journal->JournalIssue->PubDate->Month;
    $pubday=$pubmedst->MedlineCitation->Article->Journal->JournalIssue->PubDate->Day;
    $authorl=$pubmedst->MedlineCitation->Article->AuthorList->Author->LastName;
    $authorf=$pubmedst->MedlineCitation->Article->AuthorList->Author->ForeName;
    $authori=$pubmedst->MedlineCitation->Article->AuthorList->Author->Initials;

    $val1 = explode("\n", $article);
    fputcsv($fp, $val1); //Format line as CSV and write to file pointer
    $val2 = explode("\n", $pmid); //Splits a string by string in our case a newline    
    fputcsv($fp, $val2);
    $val3 = explode("\n", $journal1.=$journal2);
    fputcsv($fp, $val3);
    $val4 = explode("\n", $authorl.=$authorf);
    fputcsv($fp, $val4);
    $val5 = explode("\n", $pubyear.=$pubmonth);
    fputcsv($fp, $val5);
}

fclose($fp);
?>
4

1 回答 1

0

根据fputcsv()文档,fputcsv()期望得到一个数据数组以输出为 csv 数据。您正在传递单个字符串,因此每个字符串都成为 1 列 CSV 文件中的单个“字段”。

您需要构建一个数据数组,然后输出该数组:

$data[0] = 'foo';
$data[1] = 'bar';
$data[2] = 'baz';

fputcsv($fp, $data);

会产生

foo,bar,baz
于 2013-10-22T16:25:08.420 回答