【问题标题】:parsing xml with php using json使用 json 用 php 解析 xml
【发布时间】:2014-07-11 13:21:11
【问题描述】:

我正在构建一些东西,以便可以从 XML 文件中解析纬度和经度。问题是我有一个用户有多个 lat 和 lng(用于谷歌地图上的标记)坐标,只有第一个坐标保存在数组中。我想拥有数组中的每个坐标。看来 foreach 函数不能正常工作

这是我解析 xml 文件的 php 文件的 ajax 调用。并测试解析后的数据是否与 json 一起使用。

<html>

<head>
    <script type="text/javascript" src="jquery-2.1.0.js"></script>

    <script>


    $(function()
    {
        $.ajax(
            {
                type:"GET",
                url:"leesstudent.php",
                success:callback
            }
        );
    });


    function callback(data,status)
    {
        alert(data);
        var jsArr = JSON.parse(data);
        var coordinates = new Array();
        alert(jsArr[0]);
        for(var i=0;i<jsArr.length;i++)
        {
            $("#message").append("<p>" + jsArr[i].latitude + " " + jsArr[i].longitude + "</p>");
        }
    }

    </script>
</head>

<body>

<div id="message">
    Message..
</div>  

</body>

我解析 xml 的 php 文件,我认为 foreach 不起作用

$xml = simplexml_load_file("Database.xml");
$coordinaten = array();
$teller = 0;
foreach($xml->user as $item)
{
    $coordinaten[$teller]["latitude"] = (string)$item -> latitude;
    $coordinaten[$teller]["longitude"] = (string)$item -> longitude;
    $teller++;
}
print json_encode($coordinaten);

xml 代码

<root>

<user>
    <username>$2y$11$6SxUsvoDGlwm3Ji6BcnzCu/QyUWNy09Ny/.M9rXIpvImgJ1igJppy</username>
    <password>$2y$11$6SxUsvoDGlwm3Ji6BcnzCu7hIhAyNKtdlui1.oMdK4gQJnkZrL/Ky</password>
    <latitude>50.74688365485319</latitude><longitude>5.0701904296875</longitude>
    <latitude>51.09662294502995</latitude><longitude>4.9713134765625</longitude>
</user>

</root>

我只得到第一个纬度和经度数据,我想同时拥有(未来甚至更多)。

【问题讨论】:

标签: javascript php xml json


【解决方案1】:

您的 foreach 循环不正确。 他会循环遍历用户,但绝不会遍历您的坐标!

    foreach($xml->user as $item){

    $teller = 0;
    foreach($item -> latitude as $test )
    {
         $coordinaten[$teller]["latitude"] = (string)$test;
         $teller++;
    }

    $teller = 0;

    foreach($item -> longitude as $test2)
    {
         $coordinaten[$teller]["longitude"] = (string)$test2;
         $teller++;
    }
}

【讨论】:

    猜你喜欢
    • 2010-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多