I've tried what others have posted on stack overflow but it doesn't seem to work for me. So could anyone help please. I have this xml document with a structure of:
<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>
Then this is my PHP code to get the image to show up:
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']);
}
This is my other file:
$image = “”;
if(“” != $image){
$image = <div class=“image_holder”> $image </div>
echo $image;
}
I'm not sure how to progress forward with this. so any help would be appreciated
CodePudding user response:
It looks like you would like to fetch the image for a specific survey id. Well you can use DOM Xpath To fetch this directly:
$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);
Output:
string(22) "<img src="imagepath1">"
The content of the CDATA section inside the image element is a separate HTML fragment. You can use it directly if you trust the source of the XML or you parse it as HTML.
$htmlFragment = new DOMDocument();
$htmlFragment->loadHTML($imageForSurvey);
$htmlXpath= new DOMXpath($htmlFragment);
var_dump(
$htmlXpath->evaluate('string(//img/@src)')
);
Output:
string(10) "imagepath"
CodePudding user response:
Your example-logic is trying to create XML, not load it ;-)
First you need to find the path and/or address to the XML file, like:
$filePath = __DIR__ . '/my-file.xml';
Then load 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>";
}
}
?>
Note that you should replace
<! [CDATA[
with<![CDATA[
(without space), else you will getStartTag: invalid element name
error probably.