0

我尝试使用 xpath 从网站获取数据并将其转换为 JSON 数组。

这是我得到的结果

{"mobiles":[{"model":3,"price":"Samsung Galaxy S4 I9500"},{"model":5,"price":"Rs. 109,900"},{"model":10, "price":"Samsung Galaxy Note N7000"},{"model":12,"price":"Rs. 63,000"},{"model":17,"price":"Dialog i43"},{"model ":19,"price":"Rs.16,490"},{"model":24,"price":"Micromax X1i XTRA"},{"model":26,"price":"Rs.3,290"} ,{"model":31,"price":"Micromax X103"},{"model":33,"price":"Rs. 2,390"},{"model":38,"price":"Micromax A110帆布 2"},{"model":40,"price":"Rs. 25,990"}]}

我想打印这个数组

{"mobiles":[{"model":Samsung Galaxy S4 I9500,"price":"109,900"}等...

这是我使用的代码

    @$doc = new DOMDocument();
@$doc->loadHTMLFile($file);
$xpath = new DOMXpath($doc);
$elements = $xpath->query("//*[@class='span2 product_box']");

$models = array();
$models1 = array();

if (!is_null($elements)) {
    foreach ($elements as $element) {
        $nodes = $element->childNodes;
        foreach ($nodes as $node) {

            $modle = trim($node->nodeValue,"\t,\n,\r");
            $models[] = $modle;

        }
    }
}

$models1 = array_filter(array_map('trim', $models));

foreach($models1 as $key => $val)
{
    $result[] = array('model'=> $key, 'price'=> $val);  
}

$finalResultArray = array(
        'mobiles' => $result
);

echo json_encode($finalResultArray);

谁能帮我?

4

1 回答 1

0
$var = '{"mobiles":[{"model":3,"price":"Samsung Galaxy S4 I9500"},{"model":5,"price":"Rs. 109,900"},{"model":10,"price":"Samsung Galaxy Note N7000"},{"model":12,"price":"Rs. 63,000"},{"model":17,"price":"Dialog i43"},{"model":19,"price":"Rs. 16,490"},{"model":24,"price":"Micromax X1i XTRA"},{"model":26,"price":"Rs. 3,290"},{"model":31,"price":"Micromax X103"},{"model":33,"price":"Rs. 2,390"},{"model":38,"price":"Micromax A110 Canvas 2"},{"model":40,"price":"Rs. 25,990"}]}';

测试它:

echo "<pre>";
print_r(json_decode($var,true));
echo "</pre>";

结果:

Array
(
    [mobiles] => Array
        (
            [0] => Array
                (
                    [model] => 3
                    [price] => Samsung Galaxy S4 I9500
                )

            [1] => Array
                (
                    [model] => 5
                    [price] => Rs. 109,900
                )

            [2] => Array
                (
                    [model] => 10
                    [price] => Samsung Galaxy Note N7000
                )
)
于 2013-10-01T09:19:34.563 回答