2016-02-10 28 views
-1

我正在嘗試做一個rawurlencode,但它不像我那樣工作。我試圖編碼的數據來自javascript,我將這些信息存儲在一個變量中。除編碼之外,變量的值似乎是正確的(在幾個地方回顯)。似乎不是使用編碼的變量的值,而是使用生成值並對其進行編碼的腳本。Rawurlencode不使用變量的值,但生成值的腳本

<?php 

//getting the author name using javascript 
$author1=" 
<script type=\"text/javascript\"> 
jsauthor1 = document.getElementsByTagName(\"span\")[8].innerText; 
document.write(jsauthor1); 
</script>"; 

// checking Author name is correct 
echo $author1." : Author name after Javascript extraction". "<br>"; 
$params = array(
    "Service" => "AWSECommerceService", 
    "Operation" => "ItemSearch", 
    "AWSAccessKeyId" => "AKIAJSGKPYO6HFNCED7A", 
    "AssociateTag" => "hobbytryout0a-20", 
    "SearchIndex" => "Books", 
    "Sort" => "price", 
    "Author" => $author1, 
); 

// checking that array have correct values (taking the value of "$author" correctly)  
echo $params[Author]." : Author name after creating array using variable <br>"; 

// convert $params[Author] to a String to test the encoding 
$test = (string)$params[Author]; 
echo $test." : Author name after creating string from array"."<br>"; 
echo rawurlencode($test)." : Author name after rawurlencode"."<br>"; 
?> 

這就是我得到:

儒勒·凡爾納:使用Javascript提取後作者姓名

儒勒·凡爾納:作者姓名:使用可變

凡爾納創建數組後,作者姓名從數組創建字符串後

%20%0A%20%20%20%20%3Cscript%20type%3D%22text%2Fjava腳本%22%3E%0A%20%20%20%20jsauthor1%20%3D%20document.getElementsByTagName%28%22span%22%29%5B8%5D.innerText%3B%0A%20%20%20%20document。寫%28jsauthor1%29%3B%0A%20%20%20%20%3C%2Fscript%3E :作者姓名rawurlencode後

它不應該是儒勒%20Verne?

感謝

+0

您輸出在瀏覽器?如果是這樣,'js'在瀏覽器中執行。 PHP已經對'js'塊進行了重新編碼,因此它不會像'js'那樣執行。你的'author'也應該用引號括起來,這裏是'$ params [Author]'。 – chris85

+0

您正在對Javascript代碼進行編碼,您並未將Javascript代碼編碼爲其提取的值。 – Barmar

+0

@ chris85。感謝您的回覆。我使用js在瀏覽器上提取一個值,然後對API請求的數據進行進一步處理(不包含在本示例中,因爲我認爲其他所有工作都可以)。我認爲js正確地完成了它的工作,不是嗎?我試圖提取的值是該頁面上的「Jules Verne」。我確實重複了3個地方,並再次獲得「儒勒凡爾納」。只有當我嘗試rawurlencode沒有取得變量的值,但實際的js塊。有沒有辦法強制它對實際值進行編碼? – Viter

回答

0

爲了編碼JavaScript值,調用encodeURIComponent從JavaScript:

$author1=" 
<script type=\"text/javascript\"> 
jsauthor1 = document.getElementsByTagName(\"span\")[8].innerText; 
document.write(encodeURIComponent(jsauthor1)); 
</script>";