1

我已完成以下代码从 URL 中提取图像,但出现 XML 解析错误。如何显示包含所有 XML 输出的图像?

$error = true;
$msg = 'profile';
header('Content-type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8"?>';
if($error)
{
    echo "<response>";
    echo "<success>S</success>";
    echo "<message>".trim($msg)."</message>";
    echo "<userid>".trim($userid)."</userid>";
    echo "<username>".trim($username)."</username>";
    echo "<firstname>".trim($firstname)."</firstname>";
    echo "<lastname>".trim($lastname)."</lastname>";
    echo "<email>".trim($email)."</email>";
    echo "<follower>".trim($follower)."</follower>";
    //echo "<photo><img src=photo/".trim($photo) ." height='200' width='200'></photo>";
    echo "</response>";
}
4

3 回答 3

3

对于这样一个简单的 XML 块,您可以使用PHP 的 SimpleXML API来生成<response>XML 块。对于 XML 文档本身和没有属性的直接元素,它类似于:

$response          = new SimpleXMLElement('<response/>');
$response->success = 5;
$response->message = trim($msg);

对于带有 img 子元素和属性的 photo 元素,如下所示:

$img           = $response->addChild('photo')->addChild('img');
$img["src"]    = "photo/" . trim($photo);
$img["height"] = 200;
$img["width"]  = 200;

当您在 Google 上搜索“SimpleXML 基本示例”时,您会在 PHP 手册中找到与此类似的 PHP 示例以及更多信息。

如您所见,您不需要关心这里的 XML 编码,SimpleXML API 会为您完成这项工作。

然后输出类似直截了当:

header('Content-type: text/xml');
echo $response->asXML();

我希望这会有所帮助,示例性输出是:

<?xml version="1.0"?>
<response><success>5</success><message>profile</message><photo><img src="photo/nice-day.jpg" height="200" width="200"/></photo></response>

并美化:

<?xml version="1.0"?>
<response>
    <success>5</success>
    <message>profile</message>
    <photo>
        <img src="photo/nice-day.jpg" height="200" width="200"/>
    </photo>
</response>
于 2013-02-12T11:48:34.973 回答
1

XML 不能使用 <img src=...> 标记来显示图像。那是一个 HTML 标签。您可以拥有应用程序可以读取然后呈现的图像的 URL,但这是特定于应用程序的(即浏览器、移动电话或桌面应用程序) - 这是 XML 的重点,它是通用的,并且不依赖于单一应用。

于 2013-02-12T11:38:39.907 回答
0

使用单引号对标签进行src赋值和关闭img

       $error=true;
       $msg='profile';
       header('Content-type: text/xml');
       echo '<?xml version="1.0" encoding="UTF-8"?>';
       if($error)
       {
               echo "<response>";
               echo "<success>S</success>";
               echo "<message>".trim($msg)."</message>";
               echo "<userid>".trim($userid)."</userid>";
               echo "<username>".trim($username)."</username>";
               echo "<firstname>".trim($firstname)."</firstname>";
               echo "<lastname>".trim($lastname)."</lastname>";
               echo "<email>".trim($email)."</email>";
               echo "<follower>".trim($follower)."</follower>";
               echo "<photo><img src='photo/".trim($photo)."' height='200' width='200'></img></photo>";
               echo "</response>";
       }
于 2013-02-12T11:46:19.970 回答