【问题标题】:Google Script to replace IMPORTXML(too big xml to import with IMPORTXML)用于替换 IMPORTXML 的 Google 脚本(太大的 xml 无法使用 IMPORTXML 导入)
【发布时间】:2017-01-29 21:21:03
【问题描述】:

我想将 Google 购物 XML 导入 Google 电子表格,但 Google 电子表格显示错误:

错误 url 内容中的资源超出了最大大小。

我需要导入数据(每 6 小时更新一次),我不知道这个错误是怎么回事。

我使用的一个例子是这样的:

=IMPORTXML("http://avambu.xtechcommerce.com/datafeeds/google_shopping","//channel/item")

但使用更大的 XML。

有脚本或其他解决方案吗?

谢谢!

【问题讨论】:

  • 我还没有尝试过,但XML Service Service 似乎是 Apps Script 处理 XML 文件的方式。 “该服务允许脚本解析、导航和以编程方式创建 XML 文档。”查看代码示例指南。

标签: php xml google-apps-script google-sheets google-sheets-api


【解决方案1】:

我目前找到的最佳解决方案是使用 PHP 脚本。

$filexml = 'GoogleProductFeed.xml';
$xml = simplexml_load_file($filexml);
$xml->registerXPathNamespace('g', 'http://base.google.com/ns/1.0');

if (file_exists($filexml))  {    
   $xml = simplexml_load_file($filexml);
   $i = 1;           // Position counter
   $values = [];     // PHP array

   // Writing column headers
   $columns = array('title', 'link', 'description', 'g:availability', 'g:price', 'g:image_link', 'g:product_type',
                    'g:google_product_category', 'g:condition', 'g:identifier_exists', 'g:id');

   $fs = fopen('GoogleProductFeed.csv', 'w');
   fputcsv($fs, $columns);      
   fclose($fs);

   // Iterate through each <item> node
   $node = $xml->xpath('//item');

   foreach ($node as $n) {               
       // Iterate through each child of <item> node
       foreach ($columns as $col) {         
         $values[] = trim($xml->xpath('//item['.$i.']/'.$col)[0]);
       }    
       // Write to CSV files (appending to column headers)
       $fs = fopen('GoogleProductFeed.csv', 'a');
       fputcsv($fs, $values);      
       fclose($fs);  

       $values = [];    // Clean out array for next <item> (i.e., row)
       $i++;            // Move to next <item> (i.e., node position)
   }
}

感谢@Parfait 为另一个question 提供了更好的PHP 脚本来解决这个问题。

要让脚本自动运行,我需要使用来自 linux 服务器的 CRON。

【讨论】:

  • 如何实现php脚本到apps脚本?
  • 我没有在应用程序脚本中实现它,而是在服务器中将其转换为 CSV,然后让 Google 表格读取该文件(它更适用于 CSV,甚至是大文件)。
【解决方案2】:

我会推荐使用 UrlFetchApp.fetch();但请注意,它也仅限于 50MB 的文件大小。请在下面找到我的 Google App 脚本代码示例。

// Import .xml
var url = "URL of .xml";
// Fect .xml
var xml = UrlFetchApp.fetch(url).getContentText();
// Parse .xml
var document = XmlService.parse(xml);
// Get root
var root = document.getRootElement();
// NameSpaces 
var atom = XmlService.getNamespace('http://www.w3.org/2005/Atom');
var base = XmlService.getNamespace('http://base.google.com/ns/1.0');
// Get all children (change "entry" and NameSpace to suitable fit)
var entries = root.getChildren('entry', atom);
参考

https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多