简体   繁体   English

将PHP中的XML解析为变量

[英]Parse XML in PHP to variables

I have made a PHP script that need to receive the following XML: 我已经制作了一个PHP脚本,需要接收以下XML:

<contact_email>people@example.com</contact_email>
<contact_password>hash_in_sha256</contact_password>

I usually do stuff with JSON, but in this project I need to use XML. 我通常使用JSON进行处理,但是在此项目中,我需要使用XML。 So, to parse the JSON objects in PHP I use the following code with the following JSON: 因此,为了解析PHP中的JSON对象,我将以下代码与以下JSON结合使用:

{
    "contact_email":"people@example.com",
    "contact_password":"hash_in_sha256"
}

The script: 剧本:

$jsonBody = file_get_contents("php://input");
$jsonBody = json_decode($jsonBody);

$contact_email = $jsonBody->contact_email;
$contact_password = $jsonBody->contact_password;

But what should I do to have "people@example.com" and "hash_in_sha256" from the XML as a variable in PHP? 但是,如何使XML中的“ people@example.com”和“ hash_in_sha256”作为PHP中的变量?

Like Sahil Gulati said, use simplexml_load_string , just make sure you have valid xml, there should only be one top node, eg: 就像Sahil Gulati所说的那样,请使用simplexml_load_string ,只要确保您具有有效的xml,就应该只有一个顶级节点,例如:

$input = "<contact><contact_email>people@example.com</contact_email><contact_password>hash_in_sha256</contact_password></contact>";

$xml = simplexml_load_string($input);

echo $xml->contact_email;
echo $xml->contact_password;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM