我想要一个PHP脚本来读取.xml文件并显示某个特定值。所以例如我想找出" name"值为classname" Jack-User2"。我希望它能展示杰克"。或者,如果我想显示" John-User1"的类名的姓氏?它会显示"亨利"。
我已经尝试过搜索一下,并且找不到我需要的东西也没有多少运气。我发现了你发送订单号的那些。但我希望能够设置一个特定的值并让它找到。
我想要的大概是这样的:
<?php
$classname = "John-User1";
$xml = simplexml_load_file('myfile.xml');
echo $name; //I want the name that is for John-User1 to appear here
echo $lastname; //I want the last name here.
?>
我的XML文件:
<customerdata>
<infotype>
<usertype id="1" classname="John-User1">
<revision_id>1223</revision_id>
<firstname>John</name>
<lastname>Henry</lastname>
</usertype>
<usertype id="2" classname="Jack-User2">
<revision_id>1223</revision_id>
<name>Jack</name>
<lastname>Thompson</lastname>
</usertype>
<usertype id="3" classname="Brad-User3">
<revision_id>1223</revision_id>
<name>Brad</name>
<lastname>Henry</lastname>
</usertype>
<usertype id="4" classname="Jane-User4">
<revision_id>1223</revision_id>
<name>Jane</name>
<lastname>Harrison</lastname>
</usertype>
</infotype>
</customdata>
如果有人可以帮助这个小项目,我真的很感激。感谢
答案 0 :(得分:0)
您的XML文件中有2个错误
<name>John</name>
至</customdata>
和</customerdata>
到$classname = "John-User1";
//Read the XML file
$xmlContent = file_get_contents("txt.xml");
//Convert XML file to an object
$xmlObjects = simplexml_load_string($xmlContent);
//Create variables
$name;
$lastname;
foreach ($xmlObjects->infotype->usertype as $user) {
//Check if names are equal
if ($user["classname"] == $classname) {
$name = $user->name;
$lastname = $user->lastname;
}
}
echo $name;
echo "<br>";
echo $lastname;
下面的代码应该适合你。
John
Henry
输出:
{{1}}