uhercik
uhercik

Reputation: 3

XML change element from "object" to "string"

please someone help me?

I export products from the database via PHP to XML. I'm using this code for that(short code):

PHP:

$my_file = "xml/my_xml_file.xml";
$fh = fopen($myFile, 'w');
while($new_query = mysqli_fetch_assoc($query)) {
  $xml_file .= '<ELEMENT1>'.$new_query['element_data_text'].'</ELEMENT1>'.PHP_EOL;
}
fwrite($fh, $xml_file);
fclose($fh);

The code runs and saves a file in which I can see all the elements in order. The above mentioned element looks like this:

XML:

<ELEMENT1>Consulted disposing to moonlight ye extremity. Engage piqued in on coming. </ELEMENT1>

The problem occurs when I import XML into my customer's application. The application will return an error:

Bad data type of parameter [ELEMENT1], expected string, received object.

Upvotes: 0

Views: 52

Answers (1)

ThW
ThW

Reputation: 19482

Here are two problems visible in the source you posted.

  1. Your XML has no document element. It is invalid.
  2. You do not escape/encode the value from the database. It can break the XML or change the structure.

I suggest using XMLWriter. It is an API for just this kind of job:

$data = [
  ['element_data_text' => 'example text'],  
  ['element_data_text' => 'with special chars: < &'],
  ['element_data_text' => 'with a <strong>tag</strong>']  
];

$fileName = 'php://stdout';
$writer = new XMLWriter;
$writer->openURI($fileName);
$writer->setIndent(2);
$writer->startDocument();
$writer->startElement('DATA');

foreach ($data as $record) {
    $writer->writeElement('ELEMENT1', $record['element_data_text']);
}

$writer->endElement();
$writer->endDocument();

Output:

<?xml version="1.0"?>
<DATA>
 <ELEMENT1>example text</ELEMENT1>
 <ELEMENT1>with special chars: &lt; &amp;</ELEMENT1>
 <ELEMENT1>with a &lt;strong&gt;tag&lt;/strong&gt;</ELEMENT1>
</DATA>

The message could happen because the library the client uses returns an error object or it does generic mapping from XML to object structures (like SimpleXML).

If you generate the XML as text you should encode the dynamic values using htmlspecialchars().

$xml_file .= '<ELEMENT1>'.htmlspecialchars($new_query['element_data_text']).'</ELEMENT1>'.PHP_EOL;

Upvotes: 2

Related Questions