2015-06-02 70 views
0

我是PHP新手,來自Objective-C。我需要爲WP創建一個插件,該插件返回一個HTML表格,其中每行由來自JSON的數據填充。從本質上說,作爲一個例子,我需要return更換echo在php函數中返回html表格

$jsonurl = "http://xxxx/club/api/xxxx/category/"; 
$json = file_get_contents($jsonurl,0,null,null); 
$json_output = json_decode($json); 
//print_r ($json_output); 

echo "<table>"; 
foreach ($json_output->result as $result) 
{ 
    echo "<tr><td>".$result->id."</td><td>".$result->categoryKind."</td><td>".$result->ranking."</td>"; 
} 
echo "</table>" ; 

這一工程!我可以看到預期的輸出。但爲了通過簡碼在WP中顯示錶格,我需要returnecho。那麼我怎樣才能用return代替echo

我想:

function foobar_func(){ 

    $html= "<table>"; 

    foreach ($json_output->result as $result) 
    { 
     $html. = "<tr><td>".$result->id."</td><td>".$result->categoryKind."</td><td>".$result->ranking."</td>"; 
    } 
    $html. = "</table>" ; 

    return $html; 
} 

add_shortcode('foobar', 'foobar_func'); 

沒有成功。歡迎任何幫助。

UPDATE:同樣的結果(沒有工作)。我會退出瘋狂。

function foobar_func($json_output){ 

    $html= "<table>"; 
    foreach ($json_output->result as $result) 
    { 
     $html. = "<tr><td>".$result->id."</td><td>".$result->categoryKond."</td> <td>".$result->ranking."</td>"; 
    } 
    $html. = "</table>" ; 

    return $html; 
} 

add_shortcode('foobar', 'foobar_func'); 
+0

'$ json_output'未定義在你的函數,所以你在循環不存在的變量。 –

+0

正在將'$ json_output' var傳遞給此func? – Thamaraiselvam

+0

謝謝Marco,你可以更加解釋一下嗎? – sundsx

回答

0

調查後,我發現出路。但老實說,我不明白爲什麼這個代碼的作品。謝謝大家,讓我走上正確的道路。

代碼:

function foobar_func($json_output){ 
    $jsonurl = "http://xxxx/club/api/xxx/category/"; 
    $json = file_get_contents($jsonurl,0,null,null); 
    $json_output = json_decode($json); 
    echo "<table>"; 
    foreach ($json_output->result as $result) 
    { 
     echo "<tr><td>".$result->id."</td><td>".$result->categoryKind."</td><td>".$result->ranking."</td>"; 
    } 
    echo "</table>" ; 
    return $html; 
} 
add_shortcode('foobar', 'foobar_func'); 
+0

謝謝Nisse – sundsx

0

變量的範圍是你的問題在這裏。 $json_output在功能中不可訪問。

更改爲以下:

function foobar_func(){ 

global $json_output; 

$html= "<table>"; 

或者調用它作爲一個全局變量,可以在函數調用中傳遞。

function foobar_func($json_output){ 

然後當你調用函數,使用foobar_func($json_output)

+0

爲什麼要投票?我試試... – sundsx

+0

謝謝你,但是不能工作:( – sundsx

0

請嘗試ob_start()方法,我認爲這對你有用。 http://php.net/manual/en/function.ob-start.php

<?php 
function callback($buffer) 
{ 
    // replace all the apples with oranges 
    return (str_replace("apples", "oranges", $buffer)); 
} 

ob_start("callback"); 
?> 
<html> 
<body> 
<p>It's like comparing apples to oranges.</p> 
</body> 
</html> 
<?php 
ob_end_flush(); 
?> 
+0

謝謝你不完全有用。 – sundsx

+0

還行,試試其他一些方法:) –