2013-07-13 24 views
0

所以我想我刮項目傳遞給PHP腳本,我有我的管道:通刮項目作爲JSON PHP腳本

class TalkPhpPipeline(object): 

    def process_item(self, item, spider): 
     toPHP = json.dumps(dict(item)) 

     os.system('/usr/bin/php script.php %s' % toPHP) 
     return item 

,並在我的script.php

<? require_once('wp-config.php'); 
$string = $argv[1]; 
echo 'PHP see this '; 
var_dump($string); 

蜘蛛與script.php對話很好,但是我的script.php只能看到像這樣的{title:,如果我用item['title']替換爲PHP,那麼PHP端會看到[usomewhere only we know],我真的想傳遞給php是一個字符串,如: {'title': [u'somewhere only we know']}或只是{'title': ['somewhere only we know']},當然,我的項目包含的所有其他字段,我該怎麼做?

謝謝,

回答

1

shell在命令行中搞亂了引號。因此,使用不同的功能(如subprocess.call),使您可以指定單個參數:

subprocess.call(['/usr/bin/php', 'script.php', json.dumps(dict(item))]) 

注意,除非JSON是很短的,你可能會更好只是路過它以不同的方式來PHP,這樣的如通過管道,因爲操作系統具有命令行長度限制。

在Python中,您可以使用subprocess.Popen類將JSON傳遞給PHP腳本,該腳本可以使用fgets(STDIN)來檢索JSON。