【问题标题】:get xml response from webservice in php从 php 中的 web 服务获取 xml 响应
【发布时间】:2016-08-21 00:32:26
【问题描述】:

我正在尝试创建一个小的 web 服务,它返回一个我使用 php file_put_contents 方法检索的 xml 文件。但它不起作用。我不知道我在哪里做错了。谢谢你的帮助。我是新手!

这里是网络服务

<?php

include('confi.php');

if ($_SERVER['REQUEST_METHOD'] == "POST") {
//get data
$artist = isset($_POST['artist']) ? $_POST['artist'] : "";
$title = isset($_POST['title']) ? $_POST['title'] : "";
$dateplayed = isset($_POST['date_played']) ? $_POST['date_played'] : "";

//insert data into database
$stmt = $conn->prepare("INSERT INTO `tuto_db`.`songs` (`ID`, `artist`, `title`, "
        . "`dateplayed`) VALUES (?, ?, ?, ?);");

$stmt->bind_param(NULL, $artist, $title, $dateplayed);

$stmt->execute();

echo "New records created successfully";

$stmt->close();
$conn->close();

$array = array(
    "artist" => $artist,
    "title" => $title,
    "date_played" => $dateplayed
);

//creating object of simpleXmlElement
$xml_song_info = new SimpleXMLElement("<?xml version=\"1.0\"?><song_info></user_info>");

//function call to convert array to xml
array_to_xml($array, $xml_song_info);

$xml_file = $xml_song_info->asXML('song.xml');

//i've tried to output these variables instead of: return $xml_file;
//but i get no result
echo $xml_song_info->asXML('song.xml');

foreach ($array as $key => $value) {
    echo $key . " : " . $value;
}

return $xml_file;
}

//function defination to convert array to xml
function array_to_xml($array, &$xml_song_info) {
foreach ($array as $key => $value) {
    if (is_array($value)) {
        if (!is_numeric(($key))) {
            $subnode = $xml_song_info->addChild("$key");
            array_to_xml($value, $subnode);
        } else {
            $subnode = $xml_song_info->addChild("item$key");
            array_to_xml($value, $subnode);
        }
    } else {
        $xml_song_info->addChild("$key", htmlspecialchars("$value"));
    }
}
}

这里是请求

private $webService = 'http://localhost/wsTuto/ws_sendSongsToDb.php';

public function sendHttpPostRequest($data) {
    foreach ($data as $key => $value) {
        $this->content .= $key . '=' . $value . '&';
    }

    $this->curl = curl_init($this->webService);

    curl_setopt($this->curl, CURLOPT_HEADER, false);
    curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($this->curl, CURLOPT_POST, true);
    curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->content);

    $this->response = curl_exec($this->curl);

    $status = curl_getinfo($this->curl, CURLINFO_HTTP_CODE);
}

public function getMessage($url){
    $this->curl = curl_init();
    curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($this->curl, CURLOPT_URL, $url);

    $data = curl_exec($this->curl);

    curl_close($this->curl);
    return $data;
}

$this->sendHttpPostRequest($this->array);
        file_put_contents($this->path . '/song.xml', $this->getMessage(
        $this->webService));

这是我在文件中得到的代码

Connected successfully

conf.php

$servername = "localhost";
$username = "root";
$password = "";


try{
$conn = new PDO("mysql:host=$servername;dbname=tuto_db", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch (PDOException $ex) {
echo "Connexion failes: " . $ex->getMessage();

【问题讨论】:

  • 您注意到该代码中的错误消息了吗?至关重要。
  • 现在我注意到了,我没有注意,因为数据还是被发送到了数据库中。

标签: php xml web-services


【解决方案1】:

您返回的 HTML 实际上是 PHP 错误消息。 它有完整的调用堆栈。

根据它所说的,您想停止使用 mysql_connect() 方法(文件 C:\wamp64\www\wsTuto\confi.php)并改用 PDO 和参数化查询之类的东西。

我可以看到您正在使用mysql_real_escape_string,但值得花时间阅读 PDO 教程并尝试使用准备好的语句。看看Prepared Statements

【讨论】:

  • 我已更改为 PDO,更新了文件中的消息。还是没有xml!
  • 对于您是否拥有 Web 服务(C:\wamp64\www\wsTuto\confi.php 文件)是否属于您,我感到有些困惑?如果是,则其中仍有 mysql_connect() 语句导致 PHP 崩溃(随后无法返回 XML)
  • 我已经添加了confi.php 文件并使用prepared statement 更新了代码。文件中的信息还是一样!!
  • 好的。很好,现在没有错误,但据我所知,您的主要 Web 服务实际上并没有输出任何内容(这就是您得到一个空白文件的原因)。您有$xml_file = $xml_song_info-&gt;asXML('song.xml');,这意味着您正在写入文件系统。如果我理解正确,您需要一些与文件相呼应的东西。也许试试echo $xml_song_info-&gt;asXML(); 看看XML 是否得到回显。
  • 谢谢,但echo $xml_song_info-&gt;asXML(); 不输出任何内容。我尝试输出数组而不是 xml,以防 xml 文件出错,但我仍然在文件“Connected successfully”中得到相同的输出。我想知道错误是否不在getMessage($url)方法中,导致对Web服务的请求正在工作,因为数据已发送到数据库,但Web服务的响应除了成功之外没有输出任何其他内容联系!再次感谢
【解决方案2】:

有效的代码:

网络服务

if ($_SERVER['REQUEST_METHOD'] == "POST") {
//get data
$artist = isset($_POST['artist']) ? $_POST['artist'] : "";
$title = isset($_POST['title']) ? $_POST['title'] : "";
$dateplayed = isset($_POST['date_played']) ? $_POST['date_played'] : "";

//insert data into database
$stmt = $conn->prepare("INSERT INTO `tuto_db`.`songs` (`artist`, `title`, "
        . "`dateplayed`) VALUES ('" . $_POST['artist'] . "','" . $_POST['title'] .
        "','" . $_POST['date_played'] . "')");

$stmt->bindParam(1, $artist);
$stmt->bindParam(2, $title);
$stmt->bindParam(3, $dateplayed);

$sent = false;

if($stmt->execute()){
    $sent = true;
}

echo "New records created successfully";

$conn = NULL;

$xmlstr = <<<XML
<songinfo>
    <sent>$sent</sent>
    <title>$title</title>
    <artist>$artist</artist>           
</songinfo>
XML;

//creating object of simpleXmlElement
$xml_song_info = new SimpleXMLElement($xmlstr);

//output the xml
echo $xml_song_info->asXML();

获取 xml 响应的请求

public function sendHttpRequest($data) {

    foreach ($data as $key => $value) {
        $this->content .= $key . '=' . $value . '&';
    }

    $context_options = array(
        'http' => array(
            'method' => 'POST',
            'header' => "Content-type: application/x-www-form-urlencoded\r\n"
            . "Content-length: " . strlen($this->content) . "\r\n",
            'content' => $this->content 
        )
    );

    $context = stream_context_create($context_options);

    $this->response = file_get_contents($this->webService, false, $context);

    $fp = fopen($this->path . '/song.xml', 'ab');

    fwrite($fp, $this->response);


}

【讨论】:

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