不能在casperjs中使用PHP中的JSON字符串

时间:2014-06-16 14:10:49

标签: javascript php json casperjs

我无法在args中设置json以在casperjs脚本中使用它。

我启动第一个casperjs脚本,它在php文件中返回对象,然后我需要在另一个中使用它。 我试图这样做:

$command = "$casperjs $script $arg0";
$result = shell_exec($command);
$json_data = json_decode($result, true);
//here im getting some data from json but dont change it
$arg1 = json_encode($json_data); // i ried take $result but have the same result
$command = "$casperjs $script2 $arg1";
$json_data = shell_exec($command);

这里我有错误:

SyntaxError: Unable to parse JSON string 

$结果

{ "url": "bilko.com", "webPages": [ { "url": "bilko.com", "links": [ "/site-map", "/en/", "/biography", "/gallery", "/services", "/contacts", "/gallery/corporative", "/gallery/wedding", "/gallery/birthday", "/gallery/teambuilding" ], "content": "\n\t\n\t\t\n\t\n\t \n \n \n \n \n \n" } ], "menus": { "identifier": ".menu", "items": [ [ { "text": "Биография", "url": "/biography" }, { "text": "Галерея", "url": "/gallery" }, { "text": "Услуги", "url": "/services" }, { "text": "Контакты", "url": "/contacts" } ] ] }, "top": { "content": "/images/topLogo.png", "identifier": "header" }, "footer": { "content": "Профессиональный ведущий\nНиколай Билько\n+7 925 025 33 27\n", "identifier": "footer" }, "socBtns": [ [ "https://vk.com/id23333446", "/images/socBtns/vk.png" ] ], "sitemap": [ "/biography", "/contacts", "/en/", "/gallery", "/gallery/birthday", "/gallery/corporative", "/gallery/teambuilding", "/gallery/wedding", "/services", "/site-map", null ] }
我试图制作

的脚本2中的

site = JSON.parse(system.args[4]);

1 个答案:

答案 0 :(得分:0)

如果要将数据传递给casperjs,请将其写入文件并将路径传递给casperjs脚本。然后,您可以 read 文件的内容:

var fs = require("fs");
var site = JSON.parse(fs.read(system.args[4]));

您可以将JSON字符串写入php脚本中的临时文件:

$tmp = tempnam(dirname(__FILE__), "tmp");
file_put_contents($tmp, json_encode($json_data));
$json_data = shell_exec("$casperjs $script2 $tmp");
unlink($tmp);

可能的失败可能是:

  • 参数长度的限制(类似于120个字符)
  • $arg1
  • 中不能有空格
  • 您的shell可能会尝试解释JSON字符串中的"",因此请将整个字符串括在''中:"$casperjs $script2 '$arg1'"
  • 你也有非ansi字符可能会根据shell
  • 中断调用