[英]I want to process a XML file In php
This is my XML file 这是我的XML文件
<?xml version="1.0" encoding="UTF-8"?>
<searchresult>
<query>file</query>
<page-number>3</page-number>
<start>20</start>
<files-per-page>10</files-per-page>
<files-approx-count>6361998</files-approx-count>
<result-files>
<file>
<name>file 1</name>
<description>
descrp
</description>
<url>
http://www.example.com
</url>
</file>
<file>
<name>file 2</name>
<description>
descrp 2
</description>
<url>
http://www.example.com
</url>
</file>
</result-files>
</search-result>
i tried the following code 我尝试了以下代码
$xml = simplexml_load_file("file.xml");
foreach ($xml as $xmls):
$name =$xmls->name;
$url =$xmls->url;
echo $name.$url;
endforeach;
but no output please help. 但没有输出,请帮忙。
First thing, your XML file is not well-formed. 首先,您的XML文件格式不正确。 The root tag is
<searchresult>
while the last tag is </search-result>
. 根标记为
<searchresult>
,最后一个标记为</search-result>
。 This causes a parsing error. 这会导致解析错误。
Second thing, if your tags contain dashes, those tags cannot be used directly as variables with SimpleXML , in that case you should use a special syntax (see this: php simplexml_load_file with a dash ( - ) ). 第二件事,如果您的标记包含破折号,则这些标记不能直接用作SimpleXML的变量,在这种情况下,您应该使用特殊的语法(请参见: 带有破折号(-)的php simplexml_load_file )。 Other way to fix this is, if you control de XML syntax, change the way the XML is written and don't use dashes on tags.
解决此问题的另一种方法是,如果您控制XML语法,请更改XML的编写方式,并且不要在标签上使用破折号。
Lastly, I think you want to print out the info of files within the result-files
tag. 最后,我认为您想打印出
result-files
标记内文件的信息。
$xml = simplexml_load_file("file.xml");
foreach ($xml->{'result-files'}->file as $file) {
printFile($file);
}
function printFile($file) {
$name = trim($file->name);
$url = trim($file->url);
print "$name $url\n";
}
Output: 输出:
file 1 http://www.example.com
file 2 http://www.example.com
And you are done. 您完成了。
You're creating an object when you use the simplexml_load_file
. 当您使用
simplexml_load_file
时,您正在创建一个对象。 The object isn't necessarily iterable - but it is indexable by tag names. 该对象不一定是可迭代的-但可以通过标签名称进行索引。 try not doing the
foreach(...)
and instead just using echo $xml->name;
尝试不做
foreach(...)
,而只使用echo $xml->name;
. 。 If that doesn't work, then perhaps you're looking in the wrong directory for your file.
如果这不起作用,则可能是您在错误的目录中查找文件。 You likely need to do something like:
您可能需要执行以下操作:
EDITED TO MATCH XML FILE PROVIDED 编辑以匹配提供的XML文件
$path = $_SERVER['DOCUMENT_ROOT']."/file.xml";
$xml = simplexml_load_file($path);
echo $xml->start; //should output 20
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.