将以下代码的输出从html转换为json

时间:2016-06-29 12:16:44

标签: php json rest magento

<?php
set_time_limit(0);
error_reporting(E_ALL ^ E_NOTICE);
ini_set("display_errors",'On');
$rootDir = ""; // Root Directory Path
include($rootDir."app/Mage.php");
Mage::app("default");
$rootcatId= Mage::app()->getStore()->getRootCategoryId(); // get default
store root category id
$categories = Mage::getModel('catalog/category')->getCategories($rootcatId); // else use default category id =2
function show_categories_tree($categories) {
$array= '<ul>';
foreach($categories as $category) {
    $cat = Mage::getModel('catalog/category')->load($category->getId());
    $count = $cat->getProductCount();
    $array .= '<li>'.'<a href="' . Mage::getUrl($cat->getUrlPath()). '">' .$category->getName() . "(".$count.")</a>\n";
    if($category->hasChildren()) {
        $children = Mage::getModel('catalog/category')->getCategories($category->getId());
        $array .= show_categories_tree($children);
    }
    $array .= '</li>';
}
return $array . '</ul>';
}
echo show_categories_tree($categories);
?>

我得到的输出就像 Output Tree

我希望以json数组格式输出以下代码。所以它可以用于android webservice。

1 个答案:

答案 0 :(得分:0)

您需要提取dataview。如果clean变量中包含$array数组,则可以使用json_encode()。对于html视图,您可以创建方法html_encode()并为其中的数据添加html标记。

例如:

<?php
...
function show_categories_tree($categories, $view)
{
    $arrayCategories = categoriesConvertToArray($categories);
    switch ($view) {
        case 'json':
            return jsonView($arrayCategories); //Need array for json_encode
            break;
        case 'html':
            return htmlView($arrayCategories);
            break;
        default:
            return 'Error view';
    }
}

/**
 * Convert categories data to array
 * @return array
 */
function categoriesConvertToArray($categories)
{
    // Convert categories to array
}

function htmlView(array $categories)
{
    //Create html from array
}

function jsonView(array $categories)
{
    return json_encode($categories, JSON_PRETTY_PRINT);
}

echo show_categories_tree($categories, 'json');
echo show_categories_tree($categories, 'html');

如果您想添加xml,只需添加新方法xmlView

即可