PHP从URL引入XML

时间:2013-11-24 14:57:18

标签: javascript php xml

谢谢你的时间。 我正在做我的家庭作业项目,该项目基于Google Developer's:https://developers.google.com/maps/articles/phpsqlsearch_v3#outputxml。基本上我是使用php从URL中提取xml内容,然后使用javascript在html文件中读取它。好玩的东西吧?我以前从未写过PHP,所以我不确定我是否正确编码。下面是我的PHP:

<?php

// Get parameters from URL - PHP accepting 2 variables from index.html
$address = $_GET["address"];
$radius = $_GET["radius"];
// ------------------------------------------------------------------

// Start XML file
$dom = new \DOMDocument("1.0");

header("Content-type: text/xml");

$dom = file_get_contents('http://api.remix.bestbuy.com/v1/stores(area(' + $address + ',' + $radius + '))?show=name,address,distance,lat,lng&apiKey=fuzgmrj4nv8v9ummatn78m3k');
file_put_contents('file.xml', $dom);

echo $dom->saveXML();
?>

这是正在阅读php生成的xml的Javascript:

function searchLocationsNear(center) {
     clearLocations();

    var address = document.getElementById("addressInput").value;
     var radius = document.getElementById('radiusSelect').value;
     var searchUrl = 'phpGenXML.php?address=' + address + '&radius=' + radius;
     downloadUrl(searchUrl, function(data) {
       var xml = parseXml(data);
       var markerNodes = xml.documentElement.getElementsByTagName("marker");
       var bounds = new google.maps.LatLngBounds();

       //Create markers
       for (var i = 0; i < markerNodes.length; i++) {
         var name = markerNodes[i].getAttribute("name");
         var address = markerNodes[i].getAttribute("address");
         var distance = parseFloat(markerNodes[i].getAttribute("distance"));
         var latlng = new google.maps.LatLng(
              parseFloat(markerNodes[i].getAttribute("lat")),
              parseFloat(markerNodes[i].getAttribute("lng")));

         createOption(name, distance, i);
         createMarker(latlng, name, address);
         bounds.extend(latlng);
       }
       map.fitBounds(bounds);
       locationSelect.style.visibility = "visible";
       locationSelect.onchange = function() {
         var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
         google.maps.event.trigger(markers[markerNum], 'click');
       };
      });
    }

所以我担心在拉入XML时我做错了什么。谁能告诉我它是否好看?

谢谢, 托米

1 个答案:

答案 0 :(得分:0)

您的PHP代码确实有几个错误:

  • PHP中的连接是使用.而不是+
  • 完成的
  • 您正在创建DOMDocument的实例,然后重新分配给变量。 $dom然后变成一个字符串,您尝试调用saveXML(),这将产生错误。
  • file_put_contents()不符合您的想法。看看documentation

请改为尝试:

$address = $_GET['address'];
$radius = $_GET['radius'];

// sanitise $address and $radius

header('Content-type: application/xml');
echo file_get_contents('http://api.remix.bestbuy.com/v1/stores(area(' . $address . ',' . $radius . '))?show=name,address,distance,lat,lng&apiKey=fuzgmrj4nv8v9ummatn78m3k');