如何在PHP中从xml回显信息

如何在PHP中从xml回显信息,php,xml,Php,Xml,我对xml文件中的回显行有一些问题。 我怎么能做好呢 我试着 $test = file_get_contents(''); $test = iconv('WINDOWS-1251', 'UTF-8', $test); $test = "<xmp>".$test."</xmp>"; 我的XML: <?xml version="1.0" encoding="WINDOWS-1251"?> <rdf:RDF xml:lang="ru" xml

我对xml文件中的回显行有一些问题。 我怎么能做好呢

我试着

$test = file_get_contents('');
$test = iconv('WINDOWS-1251', 'UTF-8', $test);
$test = "<xmp>".$test."</xmp>";
我的XML:

<?xml version="1.0" encoding="WINDOWS-1251"?>
<rdf:RDF
    xml:lang="ru"
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
    xmlns:foaf="http://xmlns.com/foaf/0.1/"
    xmlns:ya="http://blogs.yandex.ru/schema/foaf/"
    xmlns:img="http://blogs.yandex.ru/schema/foaf/"
    xmlns:dc="http://purl.org/dc/elements/1.1/">
  <foaf:Person>
    <ya:publicAccess>allowed</ya:publicAccess>
    <foaf:gender>male</foaf:gender>
    <ya:created dc:date="2011-01-30T16:43:45+03:00"/>
    <ya:lastLoggedIn dc:date="2019-01-16T18:54:55+03:00"/>
    <ya:modified dc:date="2019-01-13T21:15:43+03:00"/>
  </foaf:Person>
</rdf:RDF>

允许
男性的

您最好使用SimpleXML和XPath之类的工具来访问它。至少有两种方法可以做到这一点,这两种方法都依赖于使用XPath,但您必须使用名称空间(
ya:
bit)来确保获得正确的元素。当XPath返回匹配列表时,我只使用
[0]
获取第一个匹配,如果有多个匹配,则可以使用循环

$test = file_get_contents("data.xml");
$xml = simplexml_load_string($test);

// Version 1
// Fetch the ya:created element
$created = $xml->xpath("//ya:created")[0];
// Extract the attributes and print the date
echo $created[0]->attributes("http://purl.org/dc/elements/1.1/")->date;

// Version 2
// Extract the dd:date attribute (using the @)
$createdDate = $xml->xpath("//ya:created/@dc:date")[0];
echo $createdDate;
忘了说-如果您想将这些字段用于数据库等,您可能需要将它们转换为字符串以确保它们已转换

$date = (string)$createdDate;

你的PHP版本是什么?它与phpliveregex.com上的版本不同吗?你的问题很不清楚。您是否正在尝试从XML获取数据并将其打印出来?那么您应该使用SimpleXML而不是regex。Regex不是解析基于XML的标记的好工具。顺便说一句,这个假设返回什么:
file\u get\u contents(“”)
$test = file_get_contents("data.xml");
$xml = simplexml_load_string($test);

// Version 1
// Fetch the ya:created element
$created = $xml->xpath("//ya:created")[0];
// Extract the attributes and print the date
echo $created[0]->attributes("http://purl.org/dc/elements/1.1/")->date;

// Version 2
// Extract the dd:date attribute (using the @)
$createdDate = $xml->xpath("//ya:created/@dc:date")[0];
echo $createdDate;
$date = (string)$createdDate;