我已经尝试了其他人在堆栈溢出上发布的内容,但它似乎不适合我。有人能帮帮忙吗?这个xml文档的结构是:
<surveys>
<survey>
<section>
<page>
<reference>P1</reference>
<image><! [CDATA[<img src="imagepath">]]></image>
</page>
<page>
<reference>P2</reference>
<image><! [CDATA[<img src="imagepath">]]></image>
</page>
</section>
</survey>
</surveys>
然后这是我的PHP代码让图像显示:
function xml($survey){
$result = "<surveys></surveys>";
$xml_surveys = new SimpleXMLExtended($result);
$xml_survey = $xml_surveys->addChild('survey');
if ("" != $survey[id]){
$xml_survey_>addChildData($survey['image']);
}
这是我的另一个文件:
$image = “”;
if(“” != $image){
$image = <div class=“image_holder”> $image </div>
echo $image;
}
我不知道该如何继续下去。因此,任何帮助将不胜感激
看起来您想要获取特定调查id的图像。你可以使用DOM+Xpath直接获取:
$document = new DOMDocument();
$document->loadXML($xml);
$xpath = new DOMXpath($document);
$expression = 'string(
/surveys/survey/section/page[reference="P1"]/image
)';
$imageForSurvey = $xpath->evaluate($expression);
var_dump($imageForSurvey);
输出:
string(22) "<img src="imagepath1">"
image元素中CDATA部分的内容是一个单独的HTML片段。如果您信任XML的来源,您可以直接使用它,或者将其解析为HTML。
$htmlFragment = new DOMDocument();
$htmlFragment->loadHTML($imageForSurvey);
$htmlXpath= new DOMXpath($htmlFragment);
var_dump(
$htmlXpath->evaluate('string(//img/@src)')
);
输出:
string(10) "imagepath"
您的示例逻辑正在尝试创建XML,而不是加载它;-)
首先需要找到XML文件的路径和/或地址,如:
$filePath = __DIR__ . '/my-file.xml';
然后加载XML:
<?php
$filePath = __DIR__ . '/my-file.xml';
$document = simplexml_load_file($filePath);
$surveyCount = 0;
foreach($document->survey as $survey)
{
$surveyCount = $surveyCount + 1;
echo '<h1>Survey #' . $surveyCount . '</h1>';
foreach($survey->section->page as $page)
{
echo 'Page reference: ' . $page->reference . '<br>';
// Decode your image.
$imageHtml = $page->image;
$dom = new DOMDocument();
$dom->loadHTML($imageHtml);
$xpath= new DOMXpath($dom);
$image = $xpath->evaluate('string(//img/@src)');
if(!empty($image)) {
echo '<div class=“image_holder”>' . $image . '</div>';
}
echo "<br>";
}
}
?>
注意你应该用
<![CDATA[
代替<! [CDATA[
(没有空格),否则可能会出现StartTag: invalid element name
错误。