我想将PHP文件中的内容复制到XML中:
$channel = "15";
$start = "20180124021100 +0200";
$stop = "20180124031500 +0200";
$title = "news";
$desc = "show number 50";
我需要稍后循环并添加更多频道,所以我不想只编辑XML,
我想打开XML文件并将PHP内容添加到特定位置的页面中:
XML:
<?xml version="1.0" encoding="UTF-8"?>
<channel id="1">
<display-name lang="he">1</display-name>
</channel>
// I want the content to stick to the end
<programme start="$start" stop="$stop" channel="$number">
<title lang="he">$title</title>
<desc lang="he">$desc</desc>
</programme>
// And that the next loop will be the same, will paste the content to the end as well:
<programme start="$start" stop="$stop" channel="$number">
<title lang="he">$title</title>
<desc lang="he">$desc</desc>
</programme>
答案 0 :(得分:1)
SimpleXML for PHP使用相当简单,无论是读取还是编写XML。在这个问题How to convert array to SimpleXML中,您可以找到许多关于在PHP中使用SimpleXML的建议。可以在此处找到文档:https://secure.php.net/manual/en/book.simplexml.php
答案 1 :(得分:1)
不是使用字符串来构建XML,而是应该查看现有的一个类来完成所有繁重的工作 - 它们毕竟是为此目的而设计的。查看问题中的xml,它看起来不是有效的XML,因为内容没有根节点。以下内容应该有助于开始。
<?php
$channel = "15";
$start = "20180124021100 +0200";
$stop = "20180124031500 +0200";
$title = "news";
$desc = "show number 50";
/* file path to saved xml document */
$xmlfile= __DIR__ . '/xmlfile.xml';
/* whether to display XML in browser or simply save */
$displayxml=true;
/* create DOMDocument and set args */
$dom=new DOMDocument('1.0','utf-8');
$dom->standalone=true;
$dom->formatOutput=true;
$dom->recover=true;
$dom->strictErrorChecking=true;
/* a ROOT node for the document */
$rootnode='programmes';
/* if the file already exists, open it */
if( realpath( $xmlfile ) ){
$dom->load( $xmlfile );
$root=$dom->getElementsByTagName( $rootnode )->item(0);
} else {
/* File does not exist, create root elements & content */
$root=$dom->createElement( $rootnode );
$dom->appendChild( $root );
$ochan=$dom->createElement('channel');
$ochan->setAttribute('id',1);
$root->appendChild( $ochan );
$odisp=$dom->createElement('display-name',1);
$odisp->setAttribute('lang','he');
$ochan->appendChild( $odisp );
}
/* process variables for new record/programme */
if( isset( $channel, $start, $stop, $title, $desc ) ){
$oprog=$dom->createElement('programme');
$root->appendChild( $oprog );
$oprog->setAttribute('start',$start);
$oprog->setAttribute('end',$stop);
$oprog->setAttribute('channel',$channel);
$otitle=$dom->createElement('title',$title);
$oprog->appendChild($otitle);
$otitle->setAttribute('lang','he');
$odescr=$dom->createElement('desc',$desc);
$oprog->appendChild($odescr);
$odescr->setAttribute('lang','he');
}
/* save the file */
$dom->save( $xmlfile );
/* if you want to see the generated xml in the browser */
if( $displayxml ){
header('Content-Type: application/xml');
echo $dom->saveXML();
}
?>